开发者

Is it possible to dynamically define a comparator function for a collection?

I have a basic collection :

myCollection = Backbone.Collection.extend({
  model: myModel
  url: '/theurl',
  initialize: function(){
    this.fetch();
  })
})

When initialized, the collection receives items ordered by date. I would like to be able to dynamically reorder the collection, using another model attribute (name, rating, etc.).

In the view associated with the collection, I tried to bind a click event to a callback like this :

reorderByName: function(){
  myCollect开发者_Go百科ion.comparator = function(item){
    return item.get('name');
  });
  this.render();
})

Unfortunately, that does not seem to work. Any suggestions as to how I could do it ?

Thanks.


It looks like you've only done half of what you need to do. You've given the collection its comparator, but you've not told it to resort itself. So you need to add something like this statement right before you render:

myCollection.sort();

Note that this will trigger a reset event which would be received by any object that you've bound this event to. If you wish to suppress triggering that event, you could make the call this way:

myCollection.sort({silent: true});

Hope this helps.


I found this while looking for a solution to my own issues with comparator. I thought I would add, in case anyone else finds this question, that if the models in your collections have undefined values for the property by which your comparator is sorting, the sort won't happen. Be sure to use defaults on your model if they're not required and you're gonna sort by 'em. ;)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜