在backbone.js中使用全局变量

发布于 2025-01-08 13:58:23 字数 838 浏览 2 评论 0原文

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

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

我想知道我当前的解决方案是否可以接受/良好的做法。我的 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();
    });
  }
}
}

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

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

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.

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.

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃颗糖壮壮胆 2025-01-15 13:58:23

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

var MyModel = Backbone.Model.extend({

myGlobalVar: null,
myOtherGlobalVar: null,

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

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

var MyModel = Backbone.Model.extend({

myGlobalVar: null,
myOtherGlobalVar: null,

initialize:function(){
  console.log(this.myGlobalVar)
},
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文