javascript Backbone.js - 通过构造函数传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8463537/
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
Backbone.js - passing arguments through constructors
提问by Industrial
Scenario:
I got an alert()
saying undefined
when I (try to) set the myVar
variable through the Constructor. However if I uncomment the myVar
that's living inside the myView, the alert then instead says "Hello from inside", just as one would expect.
场景:当我(尝试)通过构造函数设置变量时,
我得到了一个alert()
说法。但是,如果我取消注释位于myView 中的那个,那么警报会显示“来自内部的你好”,正如人们所期望的那样。undefined
myVar
myVar
Question:
Does this mean that I cannot set any params in the constructor of the view except backbones own params, such as model
, collection
, el
, id
, className
& tagName
?
Manual: http://documentcloud.github.com/backbone/#View-constructor
问题:
这是否意味着我不能在视图的构造函数中设置任何参数,除了主干自己的参数,例如model
, collection
, el
, id
, className
& tagName
?
手册:http: //documentcloud.github.com/backbone/#View-constructor
The code:
代码:
var myView = Backbone.View.extend({
//myVar : 'Hello from inside',
initialize: function() {
alert(this.myVar);
}
)};
new myView({myVar: 'Hello from outside'});
回答by czarchaic
Options passed into the constructor are automatically stored as this.options
传递给构造函数的选项会自动存储为 this.options
var myView = Backbone.View.extend({
myVar : 'Hello from inside',
initialize: function() {
alert(this.options.myVar);
}
)};
new myView({myVar: 'Hello from outside'});
回答by Brave Dave
As of backbone 1.1.0, the options
argument is no longer attachedautomatically to the view (see issue 2458for discussion). You now need to attach the options of each view manually:
从主干 1.1.0 开始,该options
参数不再自动附加到视图(有关讨论,请参阅问题 2458)。您现在需要手动附加每个视图的选项:
MyView = Backbone.View.extend({
initialize: function(options) {
_.extend(this, _.pick(options, "myVar", ...));
// options.myVar is now at this.myVar
}
});
new MyView({
myVar: "Hello from outside"
...
});
Alternatively you can use this mini pluginto auto-attach white-listed options, like so:
或者,您可以使用此迷你插件自动附加白名单选项,如下所示:
MyView = BaseView.extend({
options : ["myVar", ...] // options.myVar will be copied to this.myVar on initialize
});