Backbone - 是否可以将更改事件绑定到模型(除了一个属性之外)?

发布于 2024-12-15 05:29:16 字数 222 浏览 0 评论 0原文

我希望每当我更改模型的任何属性(除了一个属性)时都会触发更改事件。这可能吗?除此之外:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

物价感观 2024-12-22 05:29:16

您可以使用 model.bind('change',function() {/*...*/}) 并在函数中使用 hasChanged 检查属性:if(model.hasChanged('propIWantToExclude')) return;

You could use model.bind('change',function() {/*...*/}) and in the function use hasChanged to check the attributes: if(model.hasChanged('propIWantToExclude')) return;

自演自醉 2024-12-22 05:29:16

当“propIWantToExclude”和其他一些属性一起更改时,贾斯汀的上述答案将返回。您可能不想这样做,因此您还应该查看 model.changedAttributes 的大小:

if(model.changedAttributes.length == 1 && model.hasChanged('attrIWantToExclude')) {
    return;
}

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:

if(model.changedAttributes.length == 1 && model.hasChanged('attrIWantToExclude')) {
    return;
}
放手` 2024-12-22 05:29:16

响应 David Tuite 回答问题第一部分的请求,您可以设置一个函数来响应“已更改”事件,然后在您要忽略的属性未更改时触发自定义事件。

如果属性未更改,此逻辑将触发自定义事件:'somePropertyOtherThanThePropIWantToExcludeChanged'。如果更改了多个属性(包括您想要忽略的属性),则自定义事件也不会触发:

model.bind('change', function(){
    if( !model.hasChanged('propIWantToExclude') ){
        model.trigger('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:

model.bind('change', function(){
    if( !model.hasChanged('propIWantToExclude') ){
        model.trigger('somePropertyOtherThanThePropIWantToExcludeChanged');
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文