Can Backbone render a collection in reverse order?

后端 未结 4 2024
感动是毒
感动是毒 2021-02-09 04:11

I\'m using a Signalr hub to subscribe to events on the server. What an event is dispatched to a hub, its successfully adding the item to a Marionette CollectionView. This, in

4条回答
  •  无人共我
    2021-02-09 04:58

    There is a thread on this topic at https://github.com/marionettejs/backbone.marionette/issues/78

    Although Backbone keeps the collection sorted once you define a comparator, as @breischl pointed out, Marionette does not automatically re-render the CollectionView when order changes. In fact, Marionette listens to the add event on the collection and appends a new ItemView.

    If you want your CollectionView to always display items in reverse chronological order, and you want new items added to be prepended instead of appended, then override the appendHtml method in your 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 insert at a particular location as @dira mentioned in the comment, there is a solution posted at the link above on github by sberryman that I reproduce here for convenience (disclaimer: I haven't tested the code below personally):

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

提交回复
热议问题