Nyxynyx
Nyxynyx

Reputation: 63687

Defining variable in Meteor.js

When I define the variable lists as shown below and type lists in the console, I get the error ReferenceError: lists is not defined

var lists = new Meteor.Collection('Lists');

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "my list.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

It works only if I declare lists as a global variable:

lists = new Meteor.Collection('Lists');

Question: Why must it be scoped global?

Upvotes: 3

Views: 2945

Answers (1)

Tarang
Tarang

Reputation: 75975

To access lists in the console you need to use a Global scope as the console is outside the scope of the file itself as the Console is considered its own file.

With var you can access lists anywhere in the file.

In essence each file is wrapped in a function() {..}. This is why each file's variables can't be accessed outside of them.

The reason that variable scoping exists is slightly more complicated, but more related to the third party packages/npm modules. Each package needs to have its own scope that wont have name collisions with stuff outside.

If you want to be able to use it more normally you could put it in the /compatibility folder too.

Upvotes: 8

Related Questions