我需要保持助手动态才能获得光标。这意味着,用户可以通过单击事件更改集合,该集合用于获取列表。
但在我的 console.log
中,我得到了 window[type]
的 undefined
。我做错了什么?
所以 article.find()
可以工作,但 window[type]
不行...
导入/api/example/index.js
export const article = new Mongo.Collection('articles');
export const images = new Mongo.Collection('images');
导入/api/example/client/example.js
import { article, images } from '../';
Template.example.helpers({
list() {
const type = Template.instance().section.get();
console.log(type, window[type]); // result: 'article', undefined
return window[type].find(); // <- therefore this is NOT working
}
});
Template.example.onCreated(function() {
this.section = new ReactiveVar('article');
});
Template.example.events({
'click .target': function(event, template) {
const $this = $(event.currentTarget),
type = $this.attr('data-type');
template.section.set(type);
}
});
最佳答案
这违背了 Python 的禅宗(“显式优于隐式”),但在这里它是足够合理的。
您可以使用 import * as name from "module-name"
变体来获取所有集合(前提是它们是从该文件导出的唯一内容,否则要明确) 。
import * as collections from '../index'; //collections includes all of your collections
Template.example.helpers({
list() {
const type = Template.instance().section.get();
return collections[type].find();
}
});
这会让你得到你想要的。
关于javascript - 按变量名称选择集合 : window[type] doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622321/