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 turn, is rendered to a table.
Because the table of events is essentially a blotter, I'd like the events in reverse order and preferably only keep n-number of events.
Can Backbone 'automatically' re-render a collection in reverse order?
To go through collection in the reverse order I usually use a construction like this:
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 theappendHtml
method in yourCollectionView
as follows: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:
And add the following to extend
jQuery
to provideinsertAt
function:You can reverse your models in a collection like so...
Usually you'll have the rendering take place in your
Backbone.View
'subclass'. So you have something like:this.collection
is presumably aBackbone.Collection
subclass, and so you can just use underscore.js methods on it to get it in whatever order you like: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 ordata
attribute on the elements, and use that toinsertAfter
or similar with jQuery in yourrenderNewItem
(or similar) method.If you use lodash instead of underscore you can also do this:
From what you describe, you don't need to re-render the collection in reverse order. Just add an event for
add
on your collection in that view and have it call a function that renders the item just added and prepends it to the table.