我有一个我想要按三个不同字段排序的集合。其中一个字段是布尔值,另一个是整数,第三个是字符串。
我希望我的团队集合按照他们首先属于的organization_id排序,然后按is_primary标志(布尔值)排序,最后我希望它们按字母顺序排列。
理想情况下,我的收藏品在完成后会看起来像这样:
有一种简单的方法吗?我试过了
comparator: (team) -> [team.get('organization_id'), team.get('name'), team.get('is_primary')]
但这似乎并没有起作用。谁能为我提供一些帮助?
答案 0 :(得分:0)
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)
答案 1 :(得分:0)
我最后通过执行以下操作解决了我自己的问题:
// app/controllers/accounts/index.js
import Ember from 'ember';
export default Ember.Controller.extend({
queryParams: ['filter', 'sort'],
filter: {},
sort: '-id'
});
// app/routes/accounts/index.js
import Ember from 'ember';
export default Ember.Route.extend({
queryParams: {
filter: { refreshModel: true },
sort: { refreshModel: true }
},
model: function(params) {
return this.store.find('account', params);
},
});
// template
<th>{{input type="text" placeholder="ID" value=filter.id}}</th>