【发布时间】:2015-08-10 18:35:45
【问题描述】:
我有一个 Backbone.Collection -> Backgrid 相关的错误。行为是在一个集合被获取后,backgrid 表被渲染两次。
我对此进行了调查,发现这与 Backbone.Collection 上调用的“排序”事件有关。
Backgrid默认监听以下事件
this.listenTo(collection, "add", this.insertRow);
this.listenTo(collection, "remove", this.removeRow);
this.listenTo(collection, "sort", this.refresh);
this.listenTo(collection, "reset", this.refresh);
this.listenTo(collection, "backgrid:sort", this.sort);
this.listenTo(collection, "backgrid:edited", this.moveToNextCell);
我们没有对我们的集合进行任何前端排序,所以我想知道为什么会调用“排序”事件。
我在 Backbone.Collection 实现上对此进行了更多调查,发现以下内容:
在 fetch 之后,将在集合上调用“set”方法,其中包含以下代码块
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
var addOpts = at != null ? _.clone(options) : options;
for (var i = 0; i < toAdd.length; i++) {
if (at != null) addOpts.index = at + i;
(model = toAdd[i]).trigger('add', model, this, addOpts);
}
if (sort || orderChanged) this.trigger('sort', this, options);
if (toAdd.length || toRemove.length) this.trigger('update', this, options);
}
在这里我们可以看到排序动作本身依赖于'sort'变量。这很好,在我的情况下,这是错误的,所以根本不做任何排序。
但是,'sort' 事件本身是基于 'sort' 或 'orderChanged' 为真而被调用的。
棘手的部分是'orderChanged'即使对于导致触发此事件的第一次提取也是如此。
作为一种解决方案,我只是阻止 Backbone 监听这个事件(我们不做任何 UI 排序,所以这对我们来说是可以接受的)但我想知道为什么排序操作和排序事件是未在相同条件下完成/触发。
【问题讨论】:
标签: javascript jquery sorting events backbone.js