Can Backbone render a collection in reverse order?

2019-03-20 03:23发布

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?

8条回答
三岁会撩人
2楼-- · 2019-03-20 04:03

Backbone automatically keeps Collections in sorted order. If you want to use a non-default sort, define a comparator() function on your Collection and it will use that instead. The comparator can take either one or two arguments, see the Backbone documentation for details.

You can then render your collection in an .each() loop, and it will come out in the correct order. Adding new items to the view in sorted order is up to you, though.

查看更多
仙女界的扛把子
3楼-- · 2019-03-20 04:05

As the BackBone doesn't support reverse iteration of the collection (and it's just waste of resources to reverse or worse sort the collection) the easiest and fastest approach is to use the for loop with decreasing index over models in the collection.

for (var i = collection.length - 1; i >= 0; i--) {
    var model = collection.models[i];

    // your logic
}

It's not that elegant as sorting or reversing the collection using Underscore but the performace is much better. Try to compare different loops here just to know what costs you to write foreach instead of classic for.

查看更多
登录 后发表回答