在CompositeView中对集合进行排序的最佳方法

js9*_*999 14 javascript backbone.js marionette

我正在尝试对一个集合进行排序Marionette.CompositeView.
我有一个看起来像这样的集合:

[
   {id: 1, name: 'bar'},
   {id: 2, name: 'boo' },
   {id: 3, name: 'foo' }
]
Run Code Online (Sandbox Code Playgroud)

我需要按相反顺序对id进行排序.
实际上它只在我重新加载页面时才有效.
当我添加一个新模型时,新项目显然是随机添加到列表中.
如果我刷新页面,它们将很好地排序.

我的问题是:
1)当我添加新模型时如何解决问题?
2)有可能改进代码吗?


这是我的代码:

return Marionette.CompositeView.extend({

    initialize: function () {
        this.collection.fetch();
    },

    onRender: function () {
        var collection =  this.collection;

        collection.comparator = function (collection) {
            return - collection.get('id');
        }
    },

    onSuccess: function () {
        this.collection.add(this.messageModel);
        this.collection.sort(); // the messageModel seems to be added 
                                // apparently randomly to the list. 
                                // only if I refresh the page it will be ok
    }
})
Run Code Online (Sandbox Code Playgroud)

Der*_*ley 14

对于Marionette > = 2.0,CollectionViewCompositeView 默认维护排序.

对于Marionette <2.0和> = 1.3.0:

var MySortedView = Backbone.Marionette.CollectionView.extend({

  // ...

  appendHtml: function(collectionView, itemView, index) {
    // Already sorted when buffering.
    if (collectionView.isBuffering) {
      Backbone.Marionette.CollectionView.prototype.appendHtml.apply(this, arguments);
    }
    else {
      var childrenContainer = $(collectionView.childrenContainer || collectionView.el);
      var children = childrenContainer.children();
      if (children.size() === index) {
        childrenContainer.append(itemView.el);
      } else {
        childrenContainer.children().eq(index).before(itemView.el);
      } 
    }
  }

});
Run Code Online (Sandbox Code Playgroud)

对于Marionette <2.0或<1.3.0(与之前没有缓冲相同):

var MySortedView = Backbone.Marionette.CollectionView.extend({

  // ...

  appendHtml: function(collectionView, itemView, index) {
    var childrenContainer = $(collectionView.childrenContainer || collectionView.el);
    var children = childrenContainer.children();
    if (children.size() === index) {
      childrenContainer.append(itemView.el);
    } else {
      childrenContainer.children().eq(index).before(itemView.el);
    } 
  }

});
Run Code Online (Sandbox Code Playgroud)

CollectionView和CompositeView也是一样的.


Cla*_*jda 1

您可以在创建集合时声明 .comparator 吗?从您的代码中, .comparator 仅存在于var collectiononRender 函数内的局部变量上。如果定义正确,集合必须自动排序,并且添加新模型后不需要调用 .sort

var Chapters = new Backbone.Collection({
    comparator = function(chapter) {
        return chapter.get("id");
    };
});
Run Code Online (Sandbox Code Playgroud)