I am using Backbone.js to render a list of items e.g Books. After the list is rendered, there are options for user to sort them. So if user clicks on Sort By Title, or Sort By Author Name the list will sort itself on the client side.
window.Book = Backbone.Model.extend({ defaults: { title: "This is the title", author: "Name here" },
What is the best way to accomplish this sort using in the context of a Backbone application. Do I use a jQuery dom sorter in the AppView?
Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).
BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.
Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.
There's a discussion on this very topic that you might want to look at: https://github.com/documentcloud/backbone/issues/41.
The short of it is that when a user selects 'sort by X', you can:
comparator
function on the Collectionsort
function (which will trigger a sort
event)sort
event in your View, and (clear and) redraw the itemsAnother way to handle steps 1 & 2 is to have your own method that calls the Collection's sortBy
method and then triggers a custom event that your View can listen to.
But it seems to be the case that clearing and redrawing is the easiest (and maybe even the fastest) way to sort your View's and keep them in sync with your Collection's sort order.
You can update the comparator function and then call the sort method.
// update comparator function collection.comparator = function(model) { return model.get('name'); } // call the sort method collection.sort();
The view will be automatically re-rendered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With