Javascript 将多个属性更改绑定到 Backbone.js 模型的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8263877/
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
Correct way of binding multiple attribute changes to a Backbone.js model
提问by ericbae
I have the following code, where I bind a change to a single attribute "attribute_1".
我有以下代码,我将更改绑定到单个属性“attribute_1”。
var Mine = Backbone.Model.extend({
initialize: function() {
this.bind("change:attribute_1", function() {
console.log('changed!');
});
}
});
How do I bind two attributes? This doesn't work:
如何绑定两个属性?这不起作用:
var Mine = Backbone.Model.extend({
initialize: function() {
this.bind("change:attribute_1, change:attribute_2", function() {
console.log('changed!');
});
}
});
Nor does this:
这也没有:
var Mine = Backbone.Model.extend({
initialize: function() {
this.bind("change:attribute_1 change:attribute_2", function() {
console.log('changed!');
});
}
});
回答by Rob Hruska
As of Backbone.js 0.9.0, the bind()
function (which has been renamed to on()
) supports a space-delimited list of events:
从 Backbone.js 0.9.0 开始,该bind()
函数(已重命名为on()
)支持以空格分隔的事件列表:
model.on("change:title change:author", ...)
// equivalent to
model.bind("change:title change:author", ...)
回答by Thilo
I don't know if such a "bulk-bind" function exists (you could open a feature request for it, it seems useful).
我不知道是否存在这样的“批量绑定”功能(您可以为其打开功能请求,它似乎很有用)。
You can bind them separately:
您可以单独绑定它们:
var Mine = Backbone.Model.extend({
initialize: function() {
var listener = function() { console.log('changed'); };
this.bind("change:attribute_1", listener);
this.bind("change:attribute_2", listener);
}
});
Or you can listen to all changes (and then filter in the listener):
或者您可以收听所有更改(然后在侦听器中进行过滤):
var Mine = Backbone.Model.extend({
initialize: function() {
var listener = function() { console.log('changed'); };
this.bind("change", listener);
}
});