meteor中的全局variables

我有

var Schemas = {}; Meteor.isClient && Template.registerHelper("Schemas", Schemas); Schemas.Person = new SimpleSchema({ fullName: { type: String, index: 1, optional: true, }, email: { type: String, optional: true }, address: { type: String, optional: true }, isActive: { type: Boolean, }, age: { type: Number, optional: true } }); 

在一个文件中

 var Collections = {}; Meteor.isClient && Template.registerHelper("Collections", Collections); Persons = Collections.Persons = new Mongo.Collection("Persons"); Persons.attachSchema(Schemas.Person); 

在另一个文件中。

我得到错误ReferenceError: Schemas is not defined 。 很明显,我必须在我的collections.js文件中定义Schemas ,而不是将它们分开。 但是Meteor如何在不同的文件中使用代码呢? 我可以访问一些对象和variables,而其他人无法访问。

当您以传统的JavaScript方式定义variables时:

 var someVar = 'someValue'; 

.js文件的根目录下,Meteor使用IIFE将其范围扩展到文件。

如果你想定义一个全局variables,只需不写var ,给:

 someVar = 'someValue'; 

这将在默认情况下在所有应用程序中定义一个variables,不过您可以通过在特定的识别文件夹 (例如clientserver文件夹)中写入该声明来限制它。

但是这个variables不会被首先定义。 当Meteor运行定义它的实际代码时,它将被定义。 因此,这可能不是最好的做法,因为你要加载的顺序,它会让你的代码依赖于如何载入文件 :你把文件放在哪个文件夹,文件的名称…你的如果你稍微触摸你的架构,代码很容易出错。

正如我在另一个密切相关的post中build议,你应该直接去一个包!

使用var关键字声明的Meteor中的variables的作用域为它们声明的文件。

如果你想创build一个全局variables做到这一点

 Schemas = {} 

ReferenceError是一个节点错误。 meteor是Node上面的一个框架。

节点有一个全局范围(又名节点的globalvariables)。 如果您尝试访问未定义的全局variables,则Node(而非Meteor)抛出此错误。

浏览器也有一个叫做window的全局作用域,当未定义的variables被访问时,不会抛出ReferenceErrors。

这里有一个模式,我喜欢为类添加function(这是非常meteor):

 /lib/Helpers.js <-- Helpers for everyone (node+browser) /server/Helpers.js <-- Server helpers (node) /client/Helpers.js <-- Client helpers (browser) 

考虑这些实现:

 // /lib/Helpers.js Helpers = {/* functions */}; // Assigned to window.Helpers and global.Helpers // /server/Helpers.js Helpers = _.extend(Helpers, {/*more functions*/} // /client/Helpers.js Helpers = _.extend(Helpers, {/*more functions*/} 

这是一个微不足道的例子。 如果我不想担心加载顺序呢? 为什么不在/lib/Helpers.js中使用_.extend()?

 // /lib/Helpers.js // Helpers = {/* functions */}; // Overwrites... Helpers = _.extend(Helpers, {/* functions */}); // ReferenceError 

因为如果没有定义Helpers,你会从Node得到一个ReferenceError – 特别是用作参数的“Helpers”。 (节点知道分配助手作为global.Helpers)。

这里有两种方法可以“修复”这个问题:

1)分配助手的东西

 // /lib/Helpers.js // Helpers = Helpers || {} // would be another ReferenceError if (typeof Helpers === 'undefined') Helpers = {}; Helpers = _.extend(Helpers, {/* functions */}); 

2)使用全球的帮手

 // /lib/Helpers.js Helpers = _.extend(global.Helpers, {/* functions */}); // works in node, but... 

这两个吸。

1)的语法是可怕的。
2)在节点中工作,但在浏览器中没有全局。 所以它失败的目的。

于是我放弃了,并且第一次在lib中覆盖它,并且在覆盖之后寻找运行时错误。

如果你有一个方便的跨浏览器的语法,请注意:-) var something = something || {} something.blah = foo;

这里有一些其他的JS速记技巧 。

会话variables是全局的,可以轻松地在不同的文件/函数中访问。 Session.setPersistent用于在所有文件中持久地设置variables名称。 当他们的应用程序太大时,可能会限制使用会话variables,因为它们不会被删除,并可能在控制台中发生错误。 链接到文档: https : //docs.meteor.com/api/session.html