在Meteor.js中定义变量 [英] Defining variable in Meteor.js

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

问题描述

当我如下图所示定义变量 lists 并在控制台中键入 lists 时,出现错误 ReferenceError:列表未定义

When I define the variable lists as shown below and type lists in the console, I get the error ReferenceError: lists is not defined

var lists = new Meteor.Collection('Lists');

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "my list.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

仅当我将 lists 声明为全局变量时,它才有效:

It works only if I declare lists as a global variable:

lists = new Meteor.Collection('Lists');

问题:为什么必须将其设置为全局范围?

Question: Why must it be scoped global?

推荐答案

要在控制台中访问列表,您需要使用Global范围,因为该控制台超出了文件本身的范围,因为控制台被认为是其自己的文件.

To access lists in the console you need to use a Global scope as the console is outside the scope of the file itself as the Console is considered its own file.

使用 var ,您可以访问文件中任何位置的列表.

With var you can access lists anywhere in the file.

实质上,每个文件都包装在 function(){..} 中.这就是为什么每个文件的变量都不能在它们之外访问的原因.

In essence each file is wrapped in a function() {..}. This is why each file's variables can't be accessed outside of them.

存在变量作用域的原因稍微复杂一些,但更多与第三方包/npm模块有关.每个程序包都必须有自己的作用域,该作用域不会与外部内容发生名称冲突.

The reason that variable scoping exists is slightly more complicated, but more related to the third party packages/npm modules. Each package needs to have its own scope that wont have name collisions with stuff outside.

如果您希望能够更正常地使用它,也可以将其放在/compatibility 文件夹中.

If you want to be able to use it more normally you could put it in the /compatibility folder too.

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

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