与采集订购骨干共同意见

问题描述 投票:5回答:2

我有一个包含几个项目,应该在一个列表中访问的集合。

因此,集合中的每个元素得到它,然后将其添加到DOM到一个容器中自己的看法元素。

我的问题是:我该如何申请我的收集与比较功能的DOM实现的排序顺序?第一渲染很简单:你通过收集迭代并创建,然后附加到容器元素以正确的顺序所有视图。

但是,如果模式得到改变,并通过集合重新排序?如果元素被添加什么?我不想再渲染所有的元素,而是更新/只移动了必要的DOM节点。

sorting backbone.js collections view
2个回答
7
投票

模型添加

其中添加元素的路径是相当简单的,当你在选择的时候index模型被添加到一个集合。该指数是排序指标的基础上,如果你有一个简单的观点,应该很容易在某个索引中插入你的看法。

排序属性改变

这一个是有点棘手,你改变模型上了车,当排序属性后,我没有得心应手的答案(和我在次此挣扎以及)因为集合不会自动重新洗牌的顺序你最初添加它。

从骨干文档:

与比较功能集合不会自动重新排序如果以后更改模型属性,所以你不妨改变会影响订单模型属性排序后打电话。

所以,如果你对集合排序呼叫,它将触发reset事件,你可以钩到触发整个列表的重绘。

与列表处理是相当长的,可以严重降低用户体验,甚至诱发挂起时,这是非常低效

所以你走离开这几件事情是要知道你可以:

  • 总能找到一个模型的指数致电collection.indexOf(model)排序后
  • add事件得到一个模型的指标(第三个参数)

编辑:

想着如果一点后,我想出了这样的事情:

var Model = Backbone.Model.extend({
    initialize: function () {
        this.bind('change:name', this.onChangeName, this);
    },
    onChangeName: function ()
    {
        var index, newIndex;

        index = this.collection.indexOf(this);
        this.collection.sort({silent: true});
        newIndex = this.collection.indexOf(this);
        if (index !== newIndex)
        {
            this.trigger('reindex', newIndex);
            // or
            // this.collection.trigger('reindex', this, newIndex);

        }
    }
});

然后在你看来,你可以听

var View = Backbone.View.extend({
    initialize: function () {
        this.model.bind('reindex', this.onReindex, this);
    },
    onReindex: function (newIndex)
    {
        // execute some code that puts the view in the right place ilke
        $("ul li").eq(newIndex).after(this.$el);
    }
});

0
投票

感谢文森特的真棒解决方案。然而还有与元件,这取决于哪个方向上的重新索引元件移动的移动的问题。如果它向下移动,新位置的索引不匹配什么是在DOM中的索引。这修复它:

var Model = Backbone.Model.extend({
    initialize: function () {
        this.bind('change:name', this.onChangeName, this);
    },
    onChangeName: function () {
        var fromIndex, toIndex;

        fromIndex = this.collection.indexOf(this);
        this.collection.sort({silent: true});
        toIndex = this.collection.indexOf(this);
        if (fromIndex !== toIndex)
        {
            this.trigger('reindex', fromIndex, toIndex);
            // or
            // this.collection.trigger('reindex', this, fromIndex, toIndex);
        }
    }
});

而例如听力部分:

var View = Backbone.View.extend({
    initialize: function () {
        this.model.bind('reindex', this.onReindex, this);
    },
    onReindex: function (fromIndex, toIndex) {
        var $movingEl, $replacingEl;

        $movingEl = this.$el;
        $replacingEl = $("ul li").eq(newIndex);

        if (fromIndex < toIndex) {
            $replacingEl.after($movingEl);
        } else {
            $replacingEl.before($movingEl);
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.