Skip to content Skip to sidebar Skip to footer

How Do You Manage Namespace In Meteor?

So here is my problem : Currently, I have a dozen of functions related to WEBRTC within a template js file. My objective is to have those functions in a separate file, called webRT

Solution 1:

Make a directory called packages/ parallel to your .meteor/ directory. You can create a package that exports a single object/function. On the command line, use meteor create --package <yourpackagename> and meteor add <yourpackagename> You can edit the js file to add a namespace.

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

Then, in the package.js, simply export that namespace.

api.export('MyNamespace');

Solution 2:

You can use a common pattern of having a global object and your functions inside that object.

Greetings = {
   hello: function(name) { return"Hello "+name+" how are you?"; }
}

And then you can call it inside the template helpers :

Template.GreetingsTemplate.helpers({
   sayHello: function() { returnGreetings.hello('Maxence'); }
})

Take note of the loading order of files in Meteor, anything inside the lib folders is loaded first. If you run into problems where "Greetings" object is not defined, then its because that file was not loaded already.

Edit: You can reuse the same pattern for adding more functions in different files (you could use App = App || {} but it will throw error in Chrome for example).

App = (typeof App === 'undefined')? {} : App;App.someFunction = function(){};

or even, if you use underscore.js:

App = (typeofApp === 'undefined')? {} : App;
_.extend(App, {
  someFunction: function(){}
});

Solution 3:

Since now the regular way to use the code from another file was going through a global (server and client). As Joao suggested you can make your own global App variable where you will store or more generically a global MODULE one (basically the same solution as Joao but with explanation).

But with with the arrival of ES2015 support, we will very soon be able to have an official pattern to achieve this. However as the 1.2 does not supports yet the import/export syntax:

Note, The ES2015 modulesyntax(import/export) is not supported yet in Meteor 1.2.

If you want to start using those features earlier, I would recommend using this package which is an temporary solution to fill the current import/export gap, the meteor team development are currently looking for an elegant solution to support this.

Post a Comment for "How Do You Manage Namespace In Meteor?"