【发布时间】:2014-09-07 11:27:01
【问题描述】:
我正在从服务器获取未排序的数据,并希望使用 Backbone 将其显示在排序列表中。为此,我在集合中使用了comparator。但是,当一次将多个模型添加到集合中时,Backbone 会以不方便的顺序触发 add 事件。
这是一个说明我的问题的示例(JSFiddle:http://jsfiddle.net/5wtnjj8j/2/):
在PersonCollectionView 的initialize 函数中,我将三个人添加到集合中(请注意,他们没有正确排序)。每次 Backbone 将其中一个模型插入到集合中时,它都会触发 add 事件并调用我的 personAdded 函数。这个函数输出插入的人的名字和插入的索引。
这是我得到的输出:
insert "Alice" at index: 0
insert "Eve" at index: 2
insert "Bob" at index: 1
显然,索引是正确的(即按名称排序)。 但是为什么 Backbone 会按照指定模型的顺序而不是索引的顺序触发add事件?
我认为这种行为是违反直觉的,因为它使构建视图的排序列表变得困难。例如,假设我想为模型构建一个<ul>。插入 Alice 会起作用(因为她的索引为 0),但是当第二个 add 事件到达时,我将在索引 2 处插入 Eve,而没有先在索引 1 处收到 Bob。
Backbone 以“错误”顺序触发add事件有什么特殊原因吗?有没有办法接收按索引排序的事件?
型号
var Person = Backbone.Model.extend({
defaults: {
name: 'Unknown'
}
});
收藏
var PersonCollection = Backbone.Collection.extend({
model: Person,
comparator: 'name'
});
查看
var PersonCollectionView = Backbone.View.extend({
initialize: function() {
this.collection = new PersonCollection();
this.collection.on('add', this.personAdded, this);
var models = [{name: 'Alice'}, {name: 'Eve'}, {name: 'Bob'}];
this.collection.add(models);
},
personAdded: function(model, collection, options) {
var index = collection.indexOf(model);
var message = 'insert "' + model.get('name') + '" at index: ' + index + '<br>';
$('body').append(message);
}
});
【问题讨论】:
标签: sorting backbone.js