admin管理员组文章数量:1317131
I have a todo list with name and date. I'd like to be able to sort the list using either the title or to the date. How would I do this? Comparator allows only one type of sorting.
Thanks.
I have a todo list with name and date. I'd like to be able to sort the list using either the title or to the date. How would I do this? Comparator allows only one type of sorting.
Thanks.
Share Improve this question asked Aug 8, 2012 at 18:23 chenglouchenglou 3,6402 gold badges27 silver badges33 bronze badges 3- 1 Can I ask why you don't want to reset the collection ? There are reset triggers (for views) for this exact reason. i.e. when your sorting changes through a reset then your view re-renders. – Ashray Baruah Commented Aug 8, 2012 at 18:39
- You're right, I see no disadvantage in resetting the whole collection. Thanks. – chenglou Commented Aug 8, 2012 at 18:44
-
It is normal to
reset
a collection when data changes, in your case the entire collection, even though it's the same data but in different order – Claudiu Hojda Commented Aug 8, 2012 at 18:50
3 Answers
Reset to default 4It is possible to implement more logic into the parator so that you can abstract away some of the sorting logic:
var Collection = Backbone.Collection.extend({
model: myModel,
order: 'name'
parator: function(model) {
if (this.order === 'name') {
return model.get('name');
} else {
return model.get('date'); //or modify date into a numeric value
}
}
});
Then to change how you want it sorted:
myCollection.order = 'date';
myCollection.sort();
This will call the parator function and sort it this way.
You can listen for the resorting in a view:
this.listenTo(myCollection,'sort',this.render);
This has the added advantage that every time a model is added, it calls the parator and sorts it using whatever your current setting is, because the sorting method is stored in the collection.
You may need to look at the answer here, here is the solution provided in that post:
parator: function(item) {
return [item.get("level"), item.get("title")]
}
I think I found a method:
collection.reset(collection.sortBy(function(item){
return item.get(sortingFIeld);
}))
Where sortBy returns a new, sorted array that is passed as argument to reset. SortingField is the string property of the model.
本文标签: javascriptBackbonejs collection with multiple sortsStack Overflow
版权声明:本文标题:javascript - Backbone.js collection with multiple sorts - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742020661a2414570.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论