我很想弄清楚如何在页面加载时对主干集合进行排序。这方面的文档似乎有点薄,因为定义一个比较器肯定是不够的。我能找到的所有例子似乎都集中在比较器的定义上,这不应该是我的问题。
这是一个说明我的问题的基本示例:
$(function() {
var Item = Backbone.Model.extend({
defaults: {
amount: 0
},
sync: function(method, collection, options) {
options.url = this.methodToURL(method.toLowerCase());
Backbone.sync(method, collection, options);
},
methodToURL: function(method) {
switch(method) {
case 'create':
return "item";
break;
case 'read':
return "item/" + this.get('id');
break;
case 'update':
return "item";
break;
case 'delete':
return "item/" + this.get('id');
break;
default:
return "";
}
}
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'items',
comparator: function(item) {
return item.get("amount");
}
});
var items = new ItemList;
var ItemView = Backbone.View.extend({
tagName: 'tr',
template: _.template($("#item-template").html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var AppView = Backbone.View.extend({
el: $("#item-view"),
initialize: function() {
this.amount = $("#item-amount");
this.listenTo(items, 'add', this.addItem);
items.fetch();
},
addItem: function(item) {
var view = new ItemView({model: item});
$("#item-list").append(view.render().el);
}
});
var app = new AppView();
});