【问题标题】:Select collection by variable name: window[type] doesn't work按变量名选择集合:window[type] 不起作用
【发布时间】:2016-10-03 23:44:05
【问题描述】:

我需要让助手保持动态以获取光标。这意味着,用户可以通过单击事件更改集合,该集合用于获取列表。 但是在我的console.log 中,我得到了undefinedwindow[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


【解决方案1】:

window 对象将只包含全局变量作为属性。

然而,JavaScript 模块被隐式地赋予了它们自己的变量绑定到的范围。而且,只有全局范围可以作为变量自动访问。


您可以使用括号语法object[property],但您需要建立一个包含articleimages 的不同对象。

import { article, images } from '../';

const collections = { article, images };

// ...

或者,您可以使用 import * as name 导入所有命名导出:

import * as collections from '../';

// ...

然后,使用该对象通过type进行查找:

Template.example.helpers({
    list() {
        const type = Template.instance().section.get();
        console.log(type, collections[type]);
        return collections[type].find();
    }
});

【讨论】:

    【解决方案2】:

    这违背了 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();
        }
    });
    

    这会让你得到你想要的。

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2012-04-28
      • 2019-08-03
      • 2019-11-09
      • 2020-11-23
      • 1970-01-01
      • 2013-01-29
      • 2014-02-09
      • 2020-02-29
      相关资源
      最近更新 更多