因此,我将此子模型关联到 View 的 1 个列表项,当我编辑此模型时, View 会重新正确呈现。
但是当完整的列表模型发生变化时,我还得到了 parent 做的其他事情,并且变化事件没有在适当的级别触发,这很奇怪,
如果我手动触发 model.change(),我会看到从子模型更新的内容(意味着父模型有效更改)。
是否有自动将更改事件传播到父模型的方法?
最佳答案
您的“父”是子模型所属的集合吗?如果是这样,只要子模型的属性发生变化,集合就会收到一个变化通知。这是一个演示模型/集合更改事件的示例:
var Product = Backbone.Model.extend({});
var Products = Backbone.Collection.extend({
model: Product
});
var ProductsView = Backbone.View.extend({
initialize: function () {
this.collection.bind('change', this.onProductChange, this);
},
onProductChange: function (product) {
console.log('product with ID ' + product.get('id') + ' changed to ' + product.get('name'));
}
});
var products = new Products([{ id: 1, name: 'Book' }, { id: 2, name: 'Toy' }, { id: 3, name: 'Shirt'}]);
new ProductsView({collection:products});
products.get(1).set({ name: 'TV' }); // console: product with ID 1 changed to TV
另一方面,如果你的“父”不是你的子模型的集合,并且只有父/子关系,那么 Backbone 无法知道这种关系,所以你需要触发更改每当 child 发生变化时, parent 就会发生事件。例如:
var Parent = Backbone.Model.extend({
includeChild: function (child) {
child.bind('change', this.onChildChange, this);
},
onChildChange: function (child) {
console.log('Child with name ' + child.get('name') + ' changed.');
}
});
var Child = Backbone.Model.extend({});
var parent = new Parent();
var child = new Child({ name: 'Bob', parent: parent });
parent.includeChild(child);
child.set({name: 'Joe'}); // console: Child with name Joe changed.
这是 Backbone 事件的完整列表:http://documentcloud.github.com/backbone/#FAQ-events
关于javascript - 子模型更改事件不会传播到主干中的父模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7182888/