gpt4 book ai didi

javascript - 监听嵌套模型属性的变化

转载 作者:行者123 更新时间:2023-11-29 21:11:26 25 4
gpt4 key购买 nike

我有一个模型属性,它是一个对象:

name : "testing",
orderCondition: {
minOrderAmount: 20,
deliveryCostRequire: "MIN_ORDER_AMOUNT",
deliveryCostAmount: 5.55
}

当我这样使用 listenTo 时,render 函数没有被调用

this.listenTo(this.model, "change:orderCondition", this.render); // NO FIRING

但是当我在其他属性上使用 listenTo 时,它起作用了。

this.listenTo(this.model, "change:name", this.render); // FIRING

为什么 listenTo 看不到嵌套对象的变化,而是看到简单属性的变化?

最佳答案

使嵌套对象属性触发 change 事件的一种简单方法是用新对象替换整个对象。使用简单的 set 的最直接的方法:

model.set('orderCondition', _.extend({}, model.get('orderCondition'), {
deliveryCostRequire: "TOTAL_ORDER_AMOUNT"
}));

创建一个函数来在模型上设置嵌套属性是封装这种复杂性的好方法。

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是一个双向绑定(bind)库,它还为模型提供计算字段,实现与上述相同的效果,但具有对模型外部完全透明的额外好处。

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... */ },
}
});

使用此模型,您可以执行以下操作:

model.set('deliveryCostRequire', 'TOTAL_ORDER_AMOUNT');
model.get('deliveryCostRequire');
this.listenTo(model, 'change:deliveryCostRequire', this.render);

我还制作了a simple way to bubble up events of nested models and collections .

关于javascript - 监听嵌套模型属性的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com