Backbone.js - 自定义集合不起作用

时间:2013-01-24 12:42:34

标签: backbone.js backbone-views

在backbone.js中,为了过滤数据,我通过点击元素来获取。 我将收藏保存为新收藏。但我无法获得任何数据。

我的代码有什么问题......

我的代码:

taskListPhraseI.collection = Backbone.Collection.extend({ // collection fetching
    model:taskListPhraseI.model,
    url : 'data/data.json',
  });

taskListPhraseI.allView = Backbone.View.extend({
    el:$('.boardHolder'),
    events:{
      'click span.green' : 'filterIt'
    },
    initialize:function(){
      var that = this;_.bindAll(this);
      this.collection = new taskListPhraseI.collection(); //initial stage i am fetching
      this.collection.fetch({success:that.render});

      this.on('change:filterType', this.setNewType); //on click trigger my custom method to get the collection again
      //this.on('reset:filterType', this.setNewType);
    },
    setNewType:function(){
      var newCollection = new taskListPhraseI.collection(); // my custom collection
      newCollection.fetch(); // fetching
      this.collection.reset(newCollection,{ silent: true }) // triggering rest
      var filterType = this.filterType,
            filtered = _.filter(this.collection.models, function (item) {
                return item.get("dueDays") === filterType;
            });
            console.log(newCollection.models); // not working... why?
            console.log(this.collection.models);// works

      this.collection.reset(filtered);
    },

或我做错的方式..过滤集合

任何人都指导我正确的处理方式...... 提前谢谢

1 个答案:

答案 0 :(得分:2)

fetch是异步的。收集后将执行您的代码

newCollection.fetch({context:this}).done(function() {
  // your code
})

另外,这不是正确的reset方法用法:

this.collection.reset(newCollection,{ silent: true })

使用这种方式:

this.collection.reset(newCollection.toJSON(), {silent:true})

编辑(已添加示例)

HTML

<button>change filter</button>  

<强> JS

var url1 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=vpetrychuk&count=9'
var url2 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=derickbailey&count=9'
var collection = new (Backbone.Collection.extend({
    url : url1,
    resetWithFilter : function(key, value) {
      var query = {};
      query[key] = value;
      this.reset(this.where(query));
    }
}));

// fetch initial data
collection.fetch({dataType:'jsonp'});

$(':button').on('click', function() {
  // change url and fetch another data
  collection.url = url2;
  collection.fetch({dataType:'jsonp'}).done(function(response) {
      console.log('items count before filter:', collection.length);
    // now reset collection with selected filter
    collection.resetWithFilter('id_str', '294429621640912896');
    console.log('items count after filter:', collection.length)
  });
});

小提琴:http://jsfiddle.net/vpetrychuk/N4ZKm/