Backbone - 是否可以将更改事件绑定到模型(除了一个属性之外)?
我希望每当我更改模型的任何属性(除了一个属性)时都会触发更改事件。这可能吗?除此之外:
model.bind('change:prop1', func);
model.bind('change:prop2', func);
model.bind('change:prop3', func);
etc....
或者,有没有办法找出事件处理程序中哪个属性触发了更改?
I would like a change event to fire anytime I change any property of the model, except for one. Is this possible? Besides doing:
model.bind('change:prop1', func);
model.bind('change:prop2', func);
model.bind('change:prop3', func);
etc....
Or alternatively, is there a way to find out which property triggered the change from within the event handler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
model.bind('change',function() {/*...*/})
并在函数中使用hasChanged
检查属性:if(model.hasChanged('propIWantToExclude')) return;
You could use
model.bind('change',function() {/*...*/})
and in the function usehasChanged
to check the attributes:if(model.hasChanged('propIWantToExclude')) return;
当“propIWantToExclude”和其他一些属性一起更改时,贾斯汀的上述答案将返回。您可能不想这样做,因此您还应该查看
model.changedAttributes
的大小:Justin's answer above will return when 'propIWantToExclude' and some other attributes are changed together. You probably don't want to do that, so you should also look at the size of
model.changedAttributes
:响应 David Tuite 回答问题第一部分的请求,您可以设置一个函数来响应“已更改”事件,然后在您要忽略的属性未更改时触发自定义事件。
如果属性未更改,此逻辑将触发自定义事件:
'somePropertyOtherThanThePropIWantToExcludeChanged'
。如果更改了多个属性(包括您想要忽略的属性),则自定义事件也不会触发:Responding to David Tuite's request to answer the first part of the question, you could set up a function to respond to the "changed" event and then trigger a custom event if the property that you want to ignore was not changed.
This logic would trigger the custom event:
'somePropertyOtherThanThePropIWantToExcludeChanged'
if the property was not changed. If multiple properties were changed, including the one you want to ignore, then the custom event would also NOT fire: