【问题标题】:Why Backbone Collection 'sort' event and the sorting action itself are not triggered / done under the same conditions?为什么没有在相同条件下触发/完成 Backbone Collection 'sort' 事件和排序操作本身?
【发布时间】: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


    【解决方案1】:

    我真的不知道 backgrid 以及您当前的实现是什么,但我认为这可能是因为 backgrid 可能正在使用将比较器绑定到集合。

    然后“在正常情况下您不需要调用它,因为带有比较器的集合会在添加模型时自行排序。”

    http://backbonejs.org/#Collection-sort

    【讨论】:

    • 是的,这很有意义。对于排序本身。实际上,如果您没有比较器,那么“排序”变量将是未定义的,因此不会进行排序。然而,“排序”事件仍然被调用,因为“orderChanged”变量至少在第一次获取时总是正确的,因为它检查一个空集合(初始状态)与一个新获取的模型数组
    猜你喜欢
    • 2013-09-28
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2012-07-31
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多