Can Backbone render a collection in reverse order?

后端 未结 4 2022
感动是毒
感动是毒 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:39

    Usually you'll have the rendering take place in your Backbone.View 'subclass'. So you have something like:

    render: function() {
      this.collection.each( function(model) {
        // some rendering of each element
      }, this );
    }
    

    this.collection is presumably a Backbone.Collection subclass, and so you can just use underscore.js methods on it to get it in whatever order you like:

    this.collection.reverse().each( ... )
    this.collection.sort( function(m) { ... } ).each( ... )
    

    Etc.

    Of course, you are getting a single element from your backend, and you want to insert it in the right place without re-rendering the whole thing! So in that case just go old school and insert your sort key as a rel attribute or data attribute on the elements, and use that to insertAfter or similar with jQuery in your renderNewItem (or similar) method.

提交回复
热议问题