我的骨干收藏如下:
var model1 = new Backbone.Model({mode: 'EX'});
var model2 = new Backbone.Model({mode: 'AB'});
var model3 = new Backbone.Model({mode: 'DF'});
var model4 = new Backbone.Model({mode: 'AB'});
var model5 = new Backbone.Model({mode: 'DF'});
var model6 = new Backbone.Model({mode: 'AB'});
var myCollection = new backbone.Collection([model1,model2,model3,model4,model5, model6]);
现在我想要按照某个业务顺序对此集合进行排序,假设所有模型都具有' DF'首先是模式,然后是所有具有' AB'使用模式' EX'。模式第二个和最后一个模型。
所需输出
/*my Collection.models should contains array of models in following sequence
after sorting */
[model3, model5, model2, model4, model6, model1]
我有另一个java脚本对象,基于此我将决定这个模式序列。 e.g。
var enum = {
1: 'DF',
2: 'AB',
3: 'EX'
}
所以这里的字符串排序没用。有人可以建议我如何在我的骨干集合上编写比较器来完成这种排序
答案 0 :(得分:2)
您需要使用自定义comparator扩展默认Backbone.Collection
:
var priority= ['DF', 'AB', 'EX'];
var Collection = Backbone.Collection.extend({
comparator: function(a, b) {
return priority.indexOf(a.get('mode')) > priority.indexOf(b.get('mode'));
}
});
var myCollection = new Collection([{
mode: 'EX'
}, {
mode: 'AB'
}, {
mode: 'DF'
}, {
mode: 'AB'
}, {
mode: 'DF'
}, {
mode: 'AB'
}]);
console.log(myCollection.pluck('mode'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
&#13;
或使用对象图:
var priority = {
1: 'DF',
2: 'AB',
3: 'EX'
}
var Collection = Backbone.Collection.extend({
comparator: function(a, b) {
var i = _.findKey(priority, function(val) {
return val === a.get('mode')
});
var j = _.findKey(priority, function(val) {
return val === b.get('mode')
});
return i > j;
}
});
var myCollection = new Collection([{
mode: 'EX'
}, {
mode: 'AB'
}, {
mode: 'DF'
}, {
mode: 'AB'
}, {
mode: 'DF'
}, {
mode: 'AB'
}]);
console.log(myCollection.pluck('mode'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
&#13;
答案 1 :(得分:1)
我会翻转枚举器,以便您可以轻松索引它。
var enumerator = {
DF: 1,
AB: 2,
EX: 3
};
var YourModel = Backbone.Model.extend({
defaults: {
mode: ''
}
});
var YourCollection = Backbone.Collection.extend({
model: YourModel,
comparator: function(m) {
return enumerator[m.get('mode')];
}
});
var yourCollection = new YourCollection([
{ mode: 'EX' },
{ mode: 'AB' },
{ mode: 'DF' },
{ mode: 'AB' }
]);
console.log(yourCollection.pluck('mode')); // ["DF", "AB", "AB", "EX"]