javascript 在backbone.js 中使用全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9411896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:35:13  来源:igfitidea点击:

Using global variables in backbone.js

javascriptbackbone.jsglobal-variables

提问by Sephie

So, first question I couldn't find an answer to. Might be reason enough to ask my own first question. Apologies if the answer can be found outside the scope of backbone.js.

所以,第一个问题我找不到答案。可能有足够的理由问我自己的第一个问题。如果可以在backbone.js 范围之外找到答案,我们深表歉意。

In a backbone.js app, I need to have access to several variables in different functions, so I have to use some global variables setup.

在backbone.js 应用程序中,我需要访问不同函数中的多个变量,因此我必须使用一些全局变量设置。

I'm wondering if my current solution is acceptable/good practise. My IDE (IDEA) seems to think it isn't:

我想知道我目前的解决方案是否可以接受/良好的做法。我的 IDE (IDEA) 似乎认为它不是:

var MyModel = Backbone.Model.extend({

initialize:function(){
  var myGlobalVar, myOtherGlobalVar;//marked as unused local variable
},

myFunction:function() {          
      myGlobalVar = value;//marked as implicitly declared
      model.set({"mrJson": {"email": myGlobalVar}});
      model.save();
    });
  }
},

myOtherFunction:function() {          
      myOtherGlobalVar = otherValue;//marked as implicitly declared
      model.set({"mrJson": {"email": myGlobalVar, "other": myOtherGlobalVar}});
      model.save();
    });
  }
}
}

I tried declaring the implicitly declared globals, but that resulted in them not being accessible from the othe function.

我尝试声明隐式声明的全局变量,但这导致无法从其他函数访问它们。

Is there a proper way to do handle these global variables in backbone.js?

在backbone.js 中有处理这些全局变量的正确方法吗?

回答by lamplightdev

The way you are currently declaring the variables, they are in the function initializescope, rather than then object MyModelscope. To define the variables as Model variables (accessible to all object functions) do:

您当前声明变量的方式是,它们在函数初始化范围内,而不是在对象MyModel范围内。要将变量定义为模型变量(所有对象函数均可访问),请执行以下操作:

var MyModel = Backbone.Model.extend({

myGlobalVar: null,
myOtherGlobalVar: null,

initialize:function(){
  console.log(this.myGlobalVar)
},
...