ネストされたオブジェクトの属性トリガーを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は、双方向結合ライブラリであり、上記と同じ結果を達成するモデルの計算フィールドも提供しますが、モデルの外部から完全に透過的であるという追加の利点があります。このモデルでは
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を作りました。
この 'this.model.get(" orderCondition ")のように、model.getを使用して属性を設定できます。minOrderAmount = Some value;' –
@ ThePrzemyslaw94 '.'はバックボーンセッターではありません。バックボーンは、プロパティの直接属性にアクセスできるようにします。ここでは 'this.model.get(" orderCondition ")'イベントです。他のものはデフォルトでそのレベル以下では動作しません。 –