我在主干中有一个应用程序,我想在浮点数字段中对集合进行排序,但不要像这样:
- 9.90
- 12.50
- 100.50
- 110.50
排序结果如下:
- 100.50
- 110.50
- 12.50
- 9.90
这是我的模型:
LanguageModel = Backbone.Model.extend({});
我的收藏:
LanguageCollection = Backbone.Collection.extend({
model: LanguageModel,
sort_key: 'price', // default sort key
initData: function(data){
return data;
},
comparator: function (item) {
return item.get(this.sort_key);
},
sortByField: function (fieldName) {
this.sort_key = fieldName;
this.sort();
}
});
我的观点:
var TourView = Backbone.View.extend({
initialize: function(){
this.collection_language = new LanguageCollection();
var self = this;
var success = function(){
self.render();
};
var lang = this.importLanguages();
$.when( lang).done(success);
},
importLanguages: function(){
var languages = this.collection_language.initData(jQuery.parseJSON($('#json-languages').html()));
this.collection_language.set(languages);
return true;
},
render: function(){
$.each(this.collection_language.models, function( key, value ) {
value.attributes.price = parseFloat(value.attributes.price).toFixed(2);
});
this.collection_language.sortByField('price');
console.log(this.collection_language);
}
});
在我看来,我试图解析集合并将浮动价格转换为订单,但这并不能解决我的问题
$.each(this.collection_language.models, function( key, value ) {
value.attributes.price = parseFloat(value.attributes.price).toFixed(2);
});
this.collection_language.sortByField('price');