Using the variable name window[type] to choose a collection does not function properly

Is there a way to keep the helpers dynamic in order to obtain a cursor? The user should be able to change the collection - through a click event - that is used to retrieve a list. However, when I check my console.log, I'm seeing an undefined for window[type]. What could be causing this issue?

While article.find() seems to be functioning properly, window[type] is 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(); // <- hence, this part is NOT functioning as intended
    }
});

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 №1

While this may go against the zen of Python's principle that "explicit is better than implicit," in this case it makes sense.

If you want to access all collections from a file, you can utilize the following syntax:

import * as name from "module-name"
. Just make sure that the collections are the only things exported from that file, otherwise it's best to be explicit.

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

This approach will help you achieve your desired outcome.

Answer №2

The window object contains global variables as properties exclusively.

In JavaScript modules, variables are automatically bound to their own scope. Only the global scope is directly accessible as a variable.


To access specific data with bracket syntax, create a separate object that includes article and images:

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

const collections = { article, images };

// ...

Alternatively, import all named exports using import * as name:

import * as collections from '../';

// ...

Then, utilize this object to search by type:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript/jQuery function that fails to return a value

Upon performing the following code: test(); function test(){ $('img').load(function(){ alert(this.width); }) } An alert pops up displaying the correct image width. However, when I execute this: alert(test()); function test(){ $(&apos ...

Updating a single component within a changing array of objects in React: Best practices

I've got a question regarding React rendering that I need help with. Before I dive into the explanation, here's the link to the relevant code sandbox: https://codesandbox.io/s/list-rerendering-y3iust?file=/src/App.js Here's the situation - ...

Access to MongoDB denied on OpenShift

Encountering a 503 error when deploying a basic MongoDB and Node.js App on Openshift. Check it out here Observations from the MongoDB.log: "note: noprealloc may hurt performance in many applications... Reviewing the server.js file for the mongodb connect ...

JavaScript switch statement and case expression

Struggling to use boolean expressions within a switch statement to search for undefined values and manually change them. When using an if statement, the process is easier. For example: if statement if(Item1 == undefined) { item1 = "No"; } else if (Item ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...

Extending a universal design concept to a new theme within the MUI (Material UI) framework

I have implemented MUI's ThemeProvider and set up a Themes.js file. Within this file, I have defined the globalTheme for managing global styles such as typography and border-radius. My intention is to extend the properties of globalTheme to both light ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

The returned values from jQuery's $(this).data() appear to be outdated

Here is the code snippet I'm working with: updateColors = function() { $(".color-preview").each(function() { return $(this).css('background-color', $(this).data('color')); }); return null; }; I decided to check what&apo ...

What is the best way to properly format the retrieved JSON string using Ext JS?

After receiving the JSON data shown below, I need to change the formatting of the string values in the 'code' field. For example, 'TOTALPENDING' should display as "Pending Bonus" and 'TOTALLEFT' as "Current Bonus". How can I m ...

The watch function was triggered for a different key in the array from the one that

What is the best way to limit the watch function to only trigger for the selected key in the data array? import { useSessionStorage } from "@vueuse/core"; const defaultState = { data: [ { key: 1, name: "A" }, { key: 2, nam ...

Why does this particular check continue to generate an error, despite my prior validation to confirm its undefined status?

After making an AJAX call, I passed a collection of JSON objects. Among the datasets I received, some include the field C while others do not. Whenever I try to execute the following code snippet, it causes the system to crash. I attempted using both und ...

When you click on a row in the datatable, it will remain open and not close automatically

My setup includes a row defined as follows: oTable = $('#archivio').dataTable({ "bPaginate": false, "bInfo": false, "bAutoWidth": true, "sScrollY": 440, "bScrollCollapse": true, "sDom": '<"top"f>rt', ...

Guide to passing parameters in the pop method of Ionic 2

When using the push method in Ionic2, I attempted to pass parameters like so: this.nav.push(SecondPage, { thing1: data1, thing2: data2 }); However, I'm curious if there is a way to pass parameters in the pop() method. ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Tips for utilizing the ng-repeat scope within a nested ng-repeat

I currently have an array of objects structured as follows: expMonthByCat: {Food: [some values], Clothing: [some values] } In conjunction with this data, there exists a table formatted in the following manner: <tr data-ng-repeat="catego ...

I am seeking a way to transform this request call from JavaScript into Ajax code

My JavaScript code includes a request function, but I believe it's outdated and I'd like to convert it into an AJAX call. Can someone assist with this update? Here is the current function in my JavaScript file: function loadRest() { const ...

Checkbox acts like radio buttons in JavaScript

Currently, I have a unique setup where a table is generated dynamically based on the user's selection from a dropdown. Within this table are three checkboxes per row, with a limit of 2 checkboxes that can be checked per row. The behavior of Checkbox ...

Building a flexible table in React JS based on specific keys: a complete guide

I'm currently working on developing a dynamic table component using React JS. The component at the moment has a fixed header with the most common result keys. Some results contain additional information such as phone numbers and degrees. I'm loo ...

Unusual behavior in a for loop with node.js

Trying out some new things with node.js and running into issues with a basic for loop... for (var i = 0; i < 5; i++); {( console.log(i)) } Can anyone explain why I'm seeing 5 in the console? I was anticipating 0,1,2,3,4... ...

Updating the reference count in MongoDB

Is it possible for mongodb update to include a condition? For example, I have a database of IDs that I am managing. When someone subscribes to an ID, I want to increase the reference count, and when someone unsubscribes, I want to decrease it. If the count ...