监听嵌套模型属性的变化 [英] Listen to changes from nested model attributes
问题描述
我有一个模型属性,它是一个对象:
I have a model attribute which is an object:
name : "testing",
orderCondition: {
minOrderAmount: 20,
deliveryCostRequire: "MIN_ORDER_AMOUNT",
deliveryCostAmount: 5.55
}
当我像这样使用 listenTo
时,render
函数不会被调用
When I use listenTo
like this, the render
function is not called
this.listenTo(this.model, "change:orderCondition", this.render); // NO FIRING
但是当我在其他属性上使用 listenTo
时,它起作用了.
But when I use listenTo
on other attributes, it works.
this.listenTo(this.model, "change:name", this.render); // FIRING
为什么 listenTo
看不到嵌套对象中的变化,而是在简单属性中看到它们?
Why listenTo
doesn't see changes in nested objects but see them in simple attributes?
推荐答案
使嵌套对象属性触发 change
事件的一种简单方法是用新的对象替换整个对象.使用简单的 set
最直接的方法:
A simple way to make the nested object attribute trigger a change
event is to replace the whole object with the new one. The most straightforward way with a simple set
:
model.set('orderCondition', _.extend({}, model.get('orderCondition'), {
deliveryCostRequire: "TOTAL_ORDER_AMOUNT"
}));
创建一个函数来在模型上设置嵌套属性是封装这种复杂性的好方法.
Making a function to set nested attributes on the model is a good way to encapsulate that complexity.
var Model = Backbone.Model.extend({
setDeliveryCostRequire: function(value, options) {
// build a new object for 'orderCondition'
var newOrderCondition = _.extend({}, this.get('orderCondition'), {
deliveryCostRequire: value
});
// replace 'orderCondition' with the new object.
this.set({ orderCondition: newOrderCondition }, options);
// optionally trigger a custom event for it.
this.trigger('change:deliveryCostRequire', this, value, options);
return this;
},
});
这是基本概念.
Backbone.epoxy 是一个双向绑定库,它也为模型提供计算字段,实现与以上,但具有对模型外部完全透明的额外好处.
Backbone.epoxy is a two-way binding library which also offers computed fields for models which achieves the same as above, but with the additional benefit of being completely transparent from outside the model.
var Model = Backbone.Model.extend({
computeds: {
deliveryCostRequire: {
deps: ['orderCondition'],
get: function(orderCondition) {
return orderCondition && orderCondition.deliveryCostRequire;
},
set: function(value) {
return {
orderCondition: _.extend({}, this.get('orderCondition'), {
deliveryCostRequire: value
})
};
},
},
deliveryCostAmount: { /* ...other computed... */ },
}
});
使用此模型,您可以执行以下操作:
With this model, you could do the following:
model.set('deliveryCostRequire', 'TOTAL_ORDER_AMOUNT');
model.get('deliveryCostRequire');
this.listenTo(model, 'change:deliveryCostRequire', this.render);
我还制作了一种简单的方法来冒泡嵌套模型和集合的事件.
这篇关于监听嵌套模型属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!