Meteor 中的全局变量 [英] Global variables in Meteor

查看:21
本文介绍了Meteor 中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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 如何处理单独文件中的代码?我可以访问某些对象和变量,而其他对象和变量无法访问.

I get the error ReferenceError: Schemas is not defined. It's rather obvious that I have to define Schemas in my collections.js file instead of having them separate. But how does Meteor work with code in separate files? I can access some objects and variables while others are unaccessible.

推荐答案

当你用经典的 JavaScript 方式定义一个变量时:

When you define a variable in the classic JavaScript way :

var someVar = 'someValue';

在您的 .js 文件的根目录,Meteor 使用 IIFE.

at the root of your .js file Meteor scopes it to the file using an IIFE.

如果你想定义一个全局变量,干脆不要写var,给出:

If you want to define a global variable, simply don't write the var, giving :

someVar = 'someValue';

默认情况下,这将在您的所有应用程序中定义一个变量,尽管您可以通过将该声明写入特定识别文件夹(例如clientserver 文件夹).

This will define a variable in all your application by default, although you may restrict it by writing that declaration in a specific recognized folder (client or server folder for example).

然而,这个变量不会绝对首先被定义.当 Meteor 运行定义它的实际代码时,它将被定义.因此,这可能不是最佳实践,因为您将在加载顺序方面遇到困难,并且会使您的代码依赖于 Meteor 加载文件:你把文件放在哪个文件夹,文件名...如果你稍微接触你的架构,你的代码很容易出错.

However this variable won't be defined absolutely first. It will be defined when Meteor runs the actual code that defines it. Thus, it may not be the best practice because you're going to struggle with load order, and it will make your code dependent on how Meteor loads files: which folder you put the file in, the name of the file... Your code is prone to messy errors if you slightly touch your architecture.

正如我在 另一个密切相关的帖子你应该直接去买包裹!

As I suggested in another closely related post you should go for a package directly!

这篇关于Meteor 中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆