Backbone.js - change not triggering while the name

2019-01-09 20:38发布

In my backbone function, while the name get change the change function not at all triggering.. any one suggest me the right way to get it.. (actually i need to get changed stuff and need to update);

code :

    (function($){

var list = {};

list.model = Backbone.Model.extend({
  defaults:{
    name:'need the name'
  },
  initialize:function(){
    this.bind('change:name', function(model) {
        console.log('Model->change()', model);
    });
  }
});

list.collect = Backbone.Collection.extend({
  model:list.model,
  url : 'data/names.json',
  initialize:function(){
    this.fetch({update:true});
    this.keepUpdate();
  },
  keepUpdate:function(){
    var that = this;
    var updateData = function(){
      that.fetch({update:true});
      myTimeout = setTimeout(updateData,10000);
    }
    var myTimeout = setTimeout(updateData,10000);
  }
});


list.view = Backbone.View.extend({
  initialize:function(){
    this.collection = new list.collect();
    this.collection.on("update", this.render, this);
    this.collection.bind("change:name", function(model, attributes){
      console.log(model,attributes,'property changed'); // this is not triggering at all..
    });
  },
  render:function(data){
    _.each(this.collection.models, function(data){
      //console.log(data.get('name')); it works fine
    })
  },
  updateName:function(){
    console.log('updated called');
  }
});

var newView = new list.view();    

})(jQuery)

3条回答
Root(大扎)
2楼-- · 2019-01-09 20:50

Try removing keepUpdate from the collection and put a setTimeout in the initialize function of the view at the end. I suggest that fetch is called from the view as well as this.collection.fetch() instead of the collection's initialize function. Makes your code more reusable.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-09 21:11

Collection.fetch doesn't trigger the change event. You only get the reset event. If you need more granular events, consider calling fetch with the options {update:true}.

that.fetch({update:true});

That will trigger change event for every model that was already in the collection, and add if the model was previously not in the collection.

查看更多
地球回转人心会变
4楼-- · 2019-01-09 21:11

I'm not sure I understand your question. What are you trying to achieve ?

I don't think that fetch accepts {add:true} as a parameter (I just checked the source code and it does not appear anywhere).

When fetch completes, it only triggers a reset event (not an add). You should listen to that if you want to do something when the content of the collection changes. You can also simplify listen to change.

查看更多
登录 后发表回答