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

Best Practice for moving backbone model within a collection

本文关键字:最佳 模型 集合 移动      更新时间:2023-09-26

相关问题-

BackboneJS重新排列集合中模型的最佳方式,同时为每个模型维护0索引的有序属性

如何在集合中移动模型?

我有一个Backbone集合,以列表的形式直观地表示。此列表是可拖放的。任何项目都可以移动到集合中的任意位置(即不是排序)。我看到了一些使用集合的本机remove/add将模型放在正确位置的示例。然而,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]);
    },

我为最近的项目编写了这个解决方案。它似乎是一个类似于您所描述的界面——一个可排序的列表。此方法已绑定到集合。

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;
}

我自己的大部分代码都被删除了,但这是核心功能。Backbone的at选项使此操作变得非常简单。