How do you manage namespace in Meteor?

纵饮孤独 提交于 2019-12-25 19:00:43

问题


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 webRTCWrapper.js for example, and to call those functions in my template without using global variable.

I think I must use namespaces, am I correct ? 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/


回答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');



回答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() { return Greetings.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 = (typeof App === 'undefined')? {} : App;
_.extend(App, {
  someFunction: function(){}
});



回答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 module syntax (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.



来源:https://stackoverflow.com/questions/32782146/how-do-you-manage-namespace-in-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!