将数组与已排序的Backbone.Collection同步

Synching an array with a sorted Backbone.Collection

本文关键字:Backbone Collection 同步 排序 数组      更新时间:2023-09-26

我正在尝试将已排序的Backbone.Collection与另一个列表(例如JavaScript数组)同步。我正在使用以下代码(jsfiddle):

var coll = new Backbone.Collection();
coll.comparator = "label";
var list = []
coll.on("add", function (model, collection, options) {
    list.splice(collection.indexOf(model), 0, model.get("label"));
});
coll.add([
    {label: "1"},
    {label: "3"},
    {label: "5"},
    {label: "4"},
    {label: "2"}
]);

在本例中,这将导致以下列表:1, 2, 3, 5, 4。根本原因是,在添加事件处理程序中,Backbone.Collection已经填充了所有模型,而JS数组则没有。由于添加事件是按插入顺序而不是按排序顺序触发的,这会导致数组中出现错误的顺序。

如何更改同步方法/添加处理程序以使其正常工作?

首先需要监听sort事件

    this.listenTo(this.collection, 'sort', this.sortList);

然后将data-id标识符添加到每个列表项

    var li = $("<li>", { "data-id": model.get("label") }).html(model.get("label"));

然后根据不相等位置的对html项目进行排序

    sortList: function(collection, options) {
        collection.forEach(function(model, index) {
            var li1 = this.$el.children().eq(index),
                li2;
            if (model.get("label") != li1.data("id")) {
                li2 = this.$el.children("[data-id=" + model.get("label") + "]");
                li1.before(li2);
            }
        }, this);
    },

jsfiddle链接http://jsfiddle.net/n0fdmb8a/3/

听起来您的错误发生在初始化过程中:

var coll = new Backbone.Collection([
    {label: "1"},
    {label: "3"},
    {label: "5"},
    {label: "4"},
    {label: "2"}
], { comparator: 'label' )
var list = coll.pluck('label')
// Assuming your add-handler works, you can keep that around for future add's
coll.on("add", function (model, collection, options) {
    list.splice(collection.indexOf(model), 0, model.get("label"));
});

如果这还不够,那么您将需要做一些涉及sync事件的工作,该事件发生在add事件之后。但是,我建议您的li视图只侦听coll,然后在coll关闭addremovesort时完全重新渲染。这将完全防止试图保持两个数组彼此同步,这在编程中是不允许的。通常,您会创建一个数据结构来处理这种交互,但您的收集应该足够:

var LabelsView = Backbone.Collection.extend({
    el: '#my-list',
    template: '<% coll.each(function(model){ %> <li><%- model.get("label") %></li><% }); %>',
    initialize: function(){
        this.listenTo(this.collection, 'add remove sort', this.render)
    }
    render: function(){
        this.$el.html( this.template({ coll: this.collection }) )
    }
}) 
var labelView = new LabelsView({ collection: coll })