How do you manage the namespace in Meteor?

So, here is my problem: I currently have a dozen functions related to WEBRTC in the js template file. My goal is to have these functions in a separate file, for example webRTCWrapper.js, and to call these functions in my template without using a global variable.

I think I should use namespaces, am I right? If so, how do you use them?

EDIT: for anyone interested, this is exactly what I was looking for:

http://themeteorchef.com/snippets/using-the-module-pattern-with-meteor/

-one
javascript meteor javascript-namespaces
Sep 25 '15 at 12:23
source share
3 answers

Make the directory named packages/ parallel to the .meteor/ directory. You can create a package that exports a single object / function. At 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 package.js just export this namespace.

 api.export('MyNamespace'); 
+1
Sep 25 '15 at 13:04 on
source share

You can use the general template for the presence of a global object and your functions inside this 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() { return Greetings.hello('Maxence'); } }) 

Pay attention to the order of downloading files in Meteor; first, something is loaded inside the lib folders. If you encounter problems when the Greetings object is not defined, it is because this file has not already been downloaded.

Edit: You can reuse the same template to add additional functions to different files (you can use App = App || {}, but, for example, it will cause an error in Chrome).

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

or even if you use underscore.js:

 App = (typeof App === 'undefined')? {} : App; _.extend(App, { someFunction: function(){} }); 
+1
Sep 25 '15 at 12:34
source share

Since now the usual way to use code from another file went through the global (server and client). Since Joao suggested that you can create your own global App variable in which you will store or, in general, global MODULE alone (basically the same solution as Joao, but with an explanation).

But with the advent of ES2015 support, we will very soon get an official sample to achieve this. However, since 1.2 does not yet support import / export syntax:

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

If you want to start using these functions earlier, I would recommend using this package , which is a temporary solution to fill the current import / export gap, the development of the meteorite team is currently looking for an elegant solution to support this.

0
Sep 25 '15 at 13:04 on
source share



All Articles