Backbone.js自定义收集排序
问题描述:
我有一个Backbone.js应用程序与木偶插件。这里面有一个CompositeView中(和ItemViews)呈现的集合,我需要把它按以下方式进行排序:Backbone.js自定义收集排序
- 用户可以重新呈现ItemViews(使用jQuery排序插件),而该用户偏好被保存在一个cookie模型ID数组的形式
- 在每次重新载入时,我想对获取的集合进行排序,使其与前述的用户首选项顺序相同。
我试图在onRender钩子中手动排序collection.models数组,然后重新渲染它,但这种集合操作只是“感觉不对”(并导致无尽的渲染循环)。
是否有某种更优雅的解决方案来对集合进行排序,使模型与其他数组中定义的模型ID具有相同的顺序?
答
尝试使用集合上的Backbone.Collection#comparator方法,该方法将使用ID数组访问cookie并使用它返回1或-1。
比较功能采取两种模式,并返回-1,如果他们是同一职级和1,如果第一个模型应该来后的第一款车型要来的前一秒,0。
var MyCollection = Backbone.Collection.extend({
comparator: function(model_a, model_b) {
// In real app array comes from cookie
var order = [5, 2, 1, 4, 3],
a_index = order.indexOf(model_a.id),
b_index = order.indexOf(model_b.id);
if (a_index > b_index) {
return 1;
} else if (a_index < b_index) {
return -1;
} else {
return 0;
}
}
});
var my_collection = new MyCollection([
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 }
]);
alert(my_collection.pluck('id'));
这里是jsfiddle这个例子
答
一种方法是将映对IDS的你的“自定义”列表和集合中与ID返回型号:
var items = [
{id: 0, name: '1st', age: 40},
{id: 1, name: '2nd', age: 50},
{id: 2, name: '3rd', age: 60}
];
// order stored in cookie or localstorage ^^
var sorted = [2, 1, 0];
// our source collection
var collection = new Backbone.Collection(items);
// this could be implemented as a collection method if necessary
var sortedCollection = _.map(sorted, function (id) {
return collection.get(id);
});
var sortedIds = sortedCollection.map(function (item) { return item.id })
console.log(sortedIds);
// [2, 1, 0]
看看http://backbonejs.org/#Collection-comparator – Palpatim 2014-09-04 19:42:31