0

我有一个带有一组子模型的父模型。对于每个子模型,我想用数据呈现一个表单,然后在任何表单发生更改时更新父模型:

在父模型视图中:

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);
    });
}

更改事件被触发,但我不知道在父模型集合中引用正确子模型的正确方法。

4

2 回答 2

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 
    });
}

请注意,当在父模型或集合中进行控制时,此类绑定可能会更有效。

于 2012-07-09T17:18:04.653 回答
0

This is something that came to my mind:

  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
        }
     }
于 2012-07-09T17:07:10.300 回答