-1

在我的主干功能中,虽然名称得到更改,但更改功能根本没有触发..任何人都建议我获取它的正确方法..(实际上我需要更改内容并需要更新);

代码 :

    (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)
4

3 回答 3

1

Collection.fetch 不会触发change事件。你只会得到这个reset事件。如果您需要更精细的事件,请考虑fetch使用 options调用{update:true}

that.fetch({update:true});

change这将为已经在集合中的每个模型触发事件,add如果该模型以前不在集合中。

于 2013-01-22T07:17:02.897 回答
0

尝试从集合中删除 keepUpdate 并在最后的视图的初始化函数中放置一个 setTimeout。我建议从视图调用 fetch 以及 this.collection.fetch() 而不是集合的初始化函数。使您的代码更具可重用性。

于 2013-01-22T09:22:56.233 回答
0

我不确定我是否理解你的问题。你想达到什么目的?

我不认为 fetch 接受{add:true}作为参数(我只是检查了源代码,它没有出现在任何地方)。

完成fetch后,它只会触发一个reset事件(而不是add)。如果您想在集合的内容发生变化时做某事,您应该听一下。还可以简化收听change

于 2013-01-22T15:13:08.903 回答