2012-07-09 61 views
0

我有一個父模型與子模型的集合。Backbone JS - 更新嵌套子模型更改上的父模型集合

在父模型視圖:

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

對不起 - 我一直在upvoting,但也許不應該滴答作爲我應該:) – user888734 2012-07-09 17:14:07

回答

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

注意,這種綁定在您的父母模型或集合中進行控制時可能會更有效。

+0

大加一個代理 - 不知道!謝謝! – user888734 2012-07-09 17:25:22