javascript 模型上的骨干集合更改事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17958073/
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 collection change event on model
提问by praks5432
Is it possible to listen for a change in a model in a collection if a specific field is changed to a specific value?
如果特定字段更改为特定值,是否可以侦听集合中模型的更改?
I know that something like 'change:fieldName' exists, I'm looking for something like 'changeTo: fieldName = true'
我知道像“change:fieldName”这样的东西存在,我正在寻找像“changeTo: fieldName = true”这样的东西
回答by namero999
There's not a "shortcut" way of doing so. You have to listen to the normal change
event, and in your listener, see if the value has changed to something interesting for you. Then, propagate the event, fire a new one, or do stuff.
没有这样做的“捷径”方式。您必须收听正常change
事件,并在您的侦听器中查看该值是否已更改为您感兴趣的值。然后,传播事件,触发一个新事件,或者做一些事情。
Backbone.Collection.extend({
initialize: function() {
this.on('change:property', this.onChange);
},
onChange: function(e) {
// sorry for pseudo-code, can't remember syntax by heart, will edit
if (e.newValue == true)
myLogic();
}
}
回答by loganfsmyth
You cannot listen for an explicit value since that wouldn't work well in the general case, but you can easily bind to the general handler and run your code based on that.
您无法侦听显式值,因为这在一般情况下效果不佳,但您可以轻松绑定到通用处理程序并基于此运行您的代码。
var MyCollection = Backbone.Collection.extend({
initialize: function(models, options){
this.on('change:myProperty', this.changeMyProperty_, this);
},
changeMyProperty_: function(model, value){
if (value) this.myPropertyTrue_(model);
},
myPropertyTrue_: function(model){
// Do your logic
}
});