This section has a topic at https://github.com/marionettejs/backbone.marionette/issues/78
Although Backbone saves the collection sorted after the comparator is defined, as @breischl pointed out, Marionette does not automatically update the CollectionView when the order changes. In fact, Marionette listens for the add event in the collection and adds a new ItemView.
If you want your CollectionView always display items in reverse chronological order, and you want to add new items instead of adding, then override the appendHtml method in CollectionView as follows:
var MyCollectionView = Backbone.Marionette.CollectionView.extend({ appendHtml: function(collectionView, itemView){ collectionView.$el.prepend(itemView.el); } });
If you want to be able to embed in a specific place as @dira mentioned in the comment, there is a solution posted from the link above on github by sberryman, which I reproduce here for convenience (disclaimer: I have not tested the code below):
Change appendHtml to:
appendHtml: function(collectionView, itemView) { var itemIndex; itemIndex = collectionView.collection.indexOf(itemView.model); return collectionView.$el.insertAt(itemIndex, itemView.$el); }
And add the following to extend jQuery to provide the insertAt function:
(function($) { return jQuery.fn.insertAt = function(index, element) { var lastIndex; if (index <= 0) return this.prepend(element); lastIndex = this.children().size(); if (index >= lastIndex) return this.append(element); return $(this.children()[index - 1]).after(element); }; })(jQuery);
Tony abou-assaleh
source share