javascript - 按变量名称选择集合 : window[type] doesn't work

标签 javascript mongodb meteor ecmascript-6

我需要保持助手动态才能获得光标。这意味着,用户可以通过单击事件更改集合,该集合用于获取列表。 但在我的 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/

相关文章:

javascript - grunt.task.run 上带有变量的 Grunt for 循环

javascript - 如何防止 Mongoose 使用 ObjectID 插入而不是嵌入它

javascript - Express js app.get 回调中如何获取多个独立的响应数据

MongoDB 对象数组,按一些简单条件进行计数并按对象键分组

javascript - OpenLayers 3 中的图层切换

javascript - 从表单文本字段获取值

javascript - 在单个 JavaScript 代码库中使用 Browserify 实现多种风格/目标

javascript - 在 meteor 中将元素添加到数组 collections.update

node.js - 关于在 Meteor 包中使用 npm 模块

javascript - Meteor 的简单模式,不返回数字的方法