在集合中移动骨干模型的最佳实践

iab*_*abw 7 javascript backbone.js backbone.js-collections

相关问题 -

BackboneJS重新排列集合中模型的最佳方法,同时为每个模型保持0索引序数属性

如何在集合中移动模型?

我有一个Backbone集合,在列表中以可视方式表示.此列表是可拖放的.任何项目都可以移动到集合中的任意位置(即 - 不是排序).我已经看到一些使用集合的本机删除/添加的示例将模型放在正确的位置.但是,Backbone在添加模型时会在内部调用set,然后调用与事件相关的一堆方法并在最后对其进行排序.将模型拼接到正确位置有什么缺点吗?

删除/添加:查看第一个链接问题中的示例.

拼接:第二个例子

我目前正在使用的功能:

    moveTo: function(oldIndex, newIndex){
        oldIndex = oldIndex instanceof Backbone.Model ? this.at(oldIndex) : oldIndex;
        var spliced = this.models.splice(oldIndex, 1);
        this.models.splice(newIndex, 0, spliced[0]);
        this.trigger("move",[oldIndex,newIndex]);
    },
Run Code Online (Sandbox Code Playgroud)

Sam*_*ell 12

我为最近的项目写了这个解决方案.它似乎与您描述的类似 - 可排序列表.此方法绑定到集合.

reorder: function(new_index, original_index) {
    // If nothing is being changed, don't bother
    if (new_index === original_index) return this;
    // Get the model being moved
    var temp = collection.at(original_index);
    // Remove it
    collection.remove(temp);
    // Add it back in at the new index
    collection.add(temp, { at: new_index });
    return this;
}
Run Code Online (Sandbox Code Playgroud)

我的大部分代码都已删除,但这是核心功能.Backbone的at选项使这很容易.

  • 您可能希望将"remove"和"add"调用静音,以防止对侦听集合及其中的模型的视图进行不必要的更改.您可能还想创建自己的`move`事件,让听众做出相应的反应. (2认同)