user3142695 user3142695 - 6 months ago 14
Javascript Question

Select collection by variable name: window[type] doesn't work

I need to keep the helpers dynamic to get a cursor. That means, the user can change the collection - by click event - which is used to get a list.
But in my

console.log
I get a
undefined
for
window[type]
. What am I doing wrong?

So
article.find()
would work, but
window[type]
not...

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);
}
});

Answer

The window object will only contain global variables as properties.

However, JavaScript modules are implicitly given their own scope that variables are bound to. And, only the global scope is automatically accessible as a variable.


You can use the bracket syntax, object[property], but you'll need to establish a different object containing article and images.

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

const collections = { article, images };

// ...

Or, you can import all named exports using import * as name:

import * as collections from '../';

// ...

Then, use that object to lookup by type:

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