How can I create my own namespace for global variables in Meteor?

1k views Asked by At

I'm running into difficulty with understanding the scope of a variable that I thought would be global.
Rather than figuring it all out, I thought maybe it would be better to declare my own global namespace and keep my stuff in there.
Is this the way to do it?

client/main.js

MyNamespace = {};

client/some_other_file.js

MyNamespace.greeting = 'hello world';
2

There are 2 answers

0
David Weldon On

Yes, that's the recommended way to do it. Using a namespace like your example gives you two things:

  • It logically groups variables under a common name.
  • It minimizes the total number of variables attached to the global object.

The only thing you need to be careful of is load order. It may make more sense to put the declaration under lib or in a package.

Side note - this is essentially the same thing a package export gives you.

0
Andrea On

This is better for defining a namespace in javascript (and in Meteor):

MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;

Unfortunately it's an ugly monster (syntactically). I hope namespaces will be natively supported soon in Javascript (maybe together with classes and modules).

Usage

You can place it at the start of your files, than add your variables to it. For example:

File MyNamespace/greeting.js:

MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;

MyNamespace.greeting = 'hello world';
// ...

File MyNamespace/myFunction.js:

MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;

MyNamespace.myFunction = function() {
  // ...
}

What's wrong with MyNamespace = {};?

The point is that if you have a namespace defined on more than one file (note that inside an environment like Meteor, if you start to organize your code splitting it on multiple js files, this will happen likely) with MyNamespace = {}; the file that will be loaded for last will overwrite all definitions in previous ones.

For example:

File /client/controllers/HomeController:

Controllers = {}; // define namespace Controllers

Controllers.HomeController = ...
   // ...

File /client/controllers/LoginController:

Controllers = {}; // define namespace Controllers

Controllers.LoginController = ...
   // ...

With Meteor, LoginController will be loaded last for the alphabetic order and the instruction Controllers = {}; clears the HomeController definition that will be lost.

The solution above will prevent this.