我应该在哪里放置视图相关常量 -backbone.js
想象一下,我有一个视图,作为视图的一部分,它渲染“x”模型对象,并且仅渲染“x”。问题是,我把这个与视图相关的常量放在哪里合适?
我的猜测是做这样的事情:
myApp.MyView = Backbone.View.extend({
...
myConstant: 10,
...
render: function(){
...
//some code that uses myConstant
...
}
});
这有意义吗?
任何建议都有帮助!
Imagine that I have a view, and as part of a view it render 'x' model objects, and 'x' only. The question, where is it appropriate for me to put this view related constant?
My guess would be to do something like this:
myApp.MyView = Backbone.View.extend({
...
myConstant: 10,
...
render: function(){
...
//some code that uses myConstant
...
}
});
Does this make sense?
Any suggestions help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您想要做的是将类属性分配给视图。您可以将第二个哈希传递到扩展调用中来执行此操作。您的代码将如下所示:
您的常量可以作为 myApp.MyView.myConstant 访问。
It sounds like what you want to do is to assign a class property to the view. You can pass a second hash into your extend call to do this. Your code would look something like this:
where your constant is accessible as myApp.MyView.myConstant.
你非常接近!实际上,您只需使用 this.myConstant。这是一个工作示例...
You're very close! You'll actually just use this.myConstant. Here is a working example...
如上所述,我同意(并赞成)已接受的答案,但是为了清楚起见,我很想采用这种格式:
原因是您的视图中可能有很多 mixins,我发现当您继续添加时,可见性会变得模糊一个又一个的对象被View.extend。至少通过这种方式,您可以将其分解并在 mixins 之间添加注释。如果您使用 RequireJS 并加载一组通用的枚举/混合,那么它也更有意义。
As above I agree with (and upvoted) the accepted answer however for clarity I would be tempted to go with this format:
The reason being you might have lots of mixins for your view and I find the visibility becomes blurred when you just keep adding on object after object to View.extend. At least this way you can break it up and put comments in-between your mixins. It also makes a bit more sense if you're using RequireJS and loading in a common set of enums/mixins.
不要在扩展下初始化视图常量,它对于所有视图实例的行为就像静态常量。请改用构造函数:
更多说明这里
Don't initialize your view constants under extend, it will behave like static constant for all your view instances. Use constructor instead:
more explanation here