我有一个包含子模型集合的父模型。对于每个子模型,我想渲染一个包含数据的表单,然后在任何表单上发生更改时更新父模型:
在父模型视图中:
render: function () {
_.each(this.model.get('myChildModelCollection').models, function (myChildModel) {
var childForm = new ChildFormView({model: myChildModel})
childForm.model.on('change', function () {
//DO SOMETHING HERE TO UPDATE THE PARENT MODEL COLLECTION
})
this.$("#child-list").append(childForm.render().el);
});
}
更改事件已被触发,但我不知道在父模型集合中引用正确子模型的正确方法。
答案 0 :(得分:1)
假设您确实想在视图中设置绑定,可以将渲染方法重写为
render: function () {
var parent=this.model, coll=parent.get('myChildModelCollection');
// Backbone proxies Underscore methods on its collections
coll.each(function (myChildModel) {
var childForm = new ChildFormView({model: myChildModel})
this.$("#child-list").append(childForm.render().el);
});
coll.on('change', function(model) {
// do what you have to do with
// parent as your parent model,
// coll as your collection,
// model set to the modified child
});
}
请注意,在父模型或集合中进行控制时,此类绑定可能会更有效。
答案 1 :(得分:0)
这是我想到的:
render: function () {
var that = this;
_.each(this.model.get('myChildModelCollection').models, function (myChildModel) {
var childForm = new ChildFormView({model: myChildModel})
childForm.model.on('change', function () {
that.renderTheCollection();
})
this.$("#child-list").append(childForm.render().el);
});
},
renderTheCollection : function() {
_.each(this.model.get('myChildModelCollection').models, function (myChildModel) {
// Update
}
}