【发布时间】:2016-10-03 23:44:05
【问题描述】:
我需要让助手保持动态以获取光标。这意味着,用户可以通过单击事件更改集合,该集合用于获取列表。
但是在我的console.log 中,我得到了undefined 的window[type]。我做错了什么?
所以article.find() 可以工作,但window[type] 不行...
imports/api/example/index.js
export const article = new Mongo.Collection('articles');
export const images = new Mongo.Collection('images');
imports/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);
}
});
【问题讨论】:
-
这些不是全局变量,因此无法通过
window获得。您应该导入您需要的集合,或者在您的应用程序启动时为您注入它们(使用依赖注入)。 -
我已经导入了集合 - 请参阅第一行代码。但是,如果我在变量 (
type) 中获得了它的名称,我该如何访问这个集合? -
您可以在导入它们后创建一个常量来保存它们(例如,
const collections = {article, ...};),然后在需要时使用collections[type]。 -
可以把它放到代码里吗?
-
您能否编辑您的代码以反映您实际导入的方式,例如 2 个集合?这将使我更容易提出建议。您是否将所有集合导出到某个文件中的某个文件中?
标签: javascript mongodb meteor ecmascript-6