The best way to sort a collection in a CompositeView

巧了我就是萌 提交于 2019-12-03 23:47:56
Derick Bailey

For Marionette >= 2.0, CollectionView and CompositeView maintain sorting by default.

For Marionette < 2.0 and >= 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);
      } 
    }
  }

});

For Marionette < 2.0 or < 1.3.0 (same as before without buffering):

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

});

It's the same for CollectionView and CompositeView.

I believe the Marionette guys are considering building this into Marionette, but until that time, I've build a little mixin called Sorted which you can mix into your CollectionView and CompositeView classes. It's been heavily used in a production environment for Gitter for a long time and we find it works very well..

Can you declare the .comparator when you create the collection? from your code the .comparator exists only on local variable var collection inside onRender function. If defined correctly the collection must be automatically sorted and you do not need to call .sort after adding new model

var Chapters = new Backbone.Collection({
    comparator = function(chapter) {
        return chapter.get("id");
    };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!