编程语言
首页 > 编程语言> > javascript – 从嵌套模型属性中聆听更改

javascript – 从嵌套模型属性中聆听更改

作者:互联网

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

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看不到嵌套对象的变化,但是在简单属性中看到它们?

解决方法:

使嵌套对象属性触发更改事件的一种简单方法是使用新对象替换整个对象.使用简单集合的最简单方法:

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是一个双向绑定库,它还为模型提供了与上述相同的计算字段,但具有从模型外部完全透明的额外好处.

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.

标签:backbone-views,backbone-events,javascript,backbone-js
来源: https://codeday.me/bug/20190925/1816879.html