var Collection = Backbone.Collection.extend({
model: Backbone.Model,
sortOrder: ['organization_id', 'is_primary', 'name'],
comparator: function(a, b) {
var order = 0;
_.each(this.sortOrder, function(prop){
var aa = a.get(prop), bb = b.get(prop);
aa = _.isBoolean(aa) ? !aa : aa; // true is greater than false,
bb = _.isBoolean(bb) ? !bb : bb; // but we want to reverse that
order = aa === bb ? 0 : aa > bb ? 1 : -1;
return !order;
});
return order;
}
});
var c = new Collection([
{ is_primary: false, organization_id: 1, name: 'A' },
{ is_primary: false, organization_id: 2, name: 'A' },
{ is_primary: false, organization_id: 1, name: 'B' },
{ is_primary: false, organization_id: 2, name: 'B' },
{ is_primary: true, organization_id: 1, name: 'C' },
{ is_primary: false, organization_id: 2, name: 'C' },
{ is_primary: true, organization_id: 2, name: 'D' }
]);
c.each(function(t){
console.log('Team %s %s(org_id %d)', t.get('name'), t.get('is_primary') ? '(is_primary) ' : '', t.get('organization_id'));
});
// Outputs:
Team C (is_primary) (org_id 1)
Team A (org_id 1)
Team B (org_id 1)
Team D (is_primary) (org_id 2)
Team A (org_id 2)
Team B (org_id 2)
Team C (org_id 2)
_A比較可以被定義爲一個'sortBy'(通過一個函數,一個參數),作爲一個'排序'(傳遞需要兩個參數比較器功能),或作爲指示屬性來排序'by'_一個字符串([給定](http://backbonejs.org/#Collection-comparator)) – hindmost
因此,基本上,有是不是一個簡單的方法來做我想做的事情? – tommybond
顯然,沒有。定義'sortBy'或'sort'回調。這看起來並不難。 – hindmost