In my app I have a socket.io connection that is listening to the backend and getting updates to models held by the clients browser (which retrieves the model by id and calls set on the model attribute).
I’d like the collection to be sorted, then re-rendered as a whole in order to reflect any new ordering on the models as a result of the set (most examples seem to be around individual views being re-rendered). What’s a method of achieving this?
NB
I’ve got a backbone.js layout lifted pretty verbatim from the example todo app (this is the first backbone app).
You can achieve what you want by providing a
comparatormethod for your collection.Example:
The
comparatorin this example will cause your collection to be sorted in ascending order by thenameattribute of the models inside.Note that your collection won’t be sorted automatically when changing attribute(s) of any of its
models. By default, sorting happens only when creating new models and adding them to the collection; but thecomparatorwill be used by thecollection.sortmethod.The code above takes advantage of this by setting an event listener that simply re-sorts the collection on any
changes to thenameattributes of itsmodels.To complete the picture, we set up an appropriate event listener in the
Viewassociated with the collection to make sure it re-renders on any changes:That’s it 🙂
Relevant excerpt from the Backbone documentation: