开发者

Binding for "change" in backbone model not working

开发者 https://www.devze.com 2023-02-28 18:30 出处:网络
Here\'s the Example I was following this excellent tutorial by Thomas Davis : What is a model? Somehow the \'change\' binding is not firi开发者_运维百科ng. What am I doing wrong here?Backbone is chec

Here's the Example

I was following this excellent tutorial by Thomas Davis : What is a model? Somehow the 'change' binding is not firi开发者_运维百科ng. What am I doing wrong here?


Backbone is checking if the set value is the same as the previous value (look at https://github.com/documentcloud/backbone/blob/master/backbone.js#L210 and on).

In your example, the array is still the same but the value inside changed. This is tricky to solve. Creating a new copy of the array seems to be overhead. I would suggest to call the change event directly in your adopt function as a solution:

adopt: function(newChildsName){
  var children_array = this.get('children');
  children_array.push(newChildsName);
  this.set({children:children_array});
  this.trigger("change:children");
}

I would suggest to create an issue on backbone github repository to maybe add a "force" option to force the update (thus triggering the event) of attributes on a model.


Here is a bit awkward solution:

adopt: function(newChildsName){
  var children_array = this.get('children').splice(0);
  children_array.push(newChildsName);
  this.set({children:children_array});
}


Instead of using children as an plain array we can use it as an collection and listen to the add,remove events of the collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消