我有一个 Backbone 集合,我想根据类型对其进行分组,然后显示到 html 表格中。
我想要排序的值不按字母顺序排列。比方说:
var Animals = Backbone.Model.extend({
defaults: {
animal_name: '',
species: '',
food_preference: '',
characteristics: [],
},
initialize: function() {
console.log('Animal being created...');
}
});
我想按食物偏好排序。请注意,food_preference 只能采用 3 个值:肉食动物、草食动物和杂食动物。
我想首先在表格上显示所有杂食动物,然后是食肉动物,然后是食草动物。由于任何常规排序功能都会首先显示食肉动物,因为它是按字母顺序排列的,因此这是行不通的。
使用这些自定义功能对主干集合进行排序的最直观方法是什么?
谢谢!
最佳答案
您可以提供自定义 comparator
根据您希望设置的顺序返回数字的方法:
var AnimalsCollection = Backbone.Collection.extend({
comparator: function(m) {
switch (m.get('food_preference')) {
case 'omnivores': return 1;
case 'carnivore': return 2;
case 'herbivores': return 3;
default: return Infinity;
}
}
});
还有演示
var c = new Backbone.Collection([
{animal_name: 3, food_preference: 'herbivores'},
{animal_name: 2, food_preference: 'carnivore'},
{animal_name: 1, food_preference: 'omnivores'},
{animal_name: 4}
]);
console.log(c.pluck('animal_name'));
c.comparator = function(m) {
switch (m.get('food_preference')) {
case 'omnivores': return 1;
case 'carnivore': return 2;
case 'herbivores': return 3;
default: return Infinity;
}
};
c.sort();
console.log(c.pluck('animal_name'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
关于javascript - 自定义排序 Backbone 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33106755/