0

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

或者我做错的方式..过滤收藏

任何人都可以指导我正确的处理方式...在此先感谢

4

1 回答 1

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/

于 2013-01-24T13:19:27.653 回答