简体   繁体   中英

Sorting Collections Backbone.js

I'm attempting to learn Backbone.js and have run into a bit of a wall when it comes to sorting.

My model is a song, and it has the attributes 'title', 'minutes', 'seconds', and 'order'.

Right now, I simply add each song to my View by adding them as list elements to an unordered list. My function looks like this:

$('#oList', this.el).append("<li id = 'song' > Song Name: " + song.get('title') + " Minutes: " + song.get('minutes') + " Seconds" + song.get('seconds') + "</li>");

They are also added to a collection before being appended.

I want to be able to sort based on title (alphabetically) and song length (numerically, based on the total of minutes and seconds).

Is there any easy way to do this? I've read about the sort() function in Backbone, as well as the comparator, but I'm still not seeing what I am supposed to be doing. Mainly, how will all my elements be added back into my View? When I want to sort by title, do I have to clear the list in my HTML and somehow re-add each element?

Any direction is greatly appreciated.

When you define a comparator, Backbone uses Underscores sort and sortBy methods to keep your collection sorted as you add models. Comparator is an attribute set on the Collection that can either be a string (which will be the property name in your data used by sortBy - http://underscorejs.org/#sortBy ) or a function.

Here is a basic example:

var Song = Backbone.Model.extend(),
    SongCollection = Backbone.Collection.extend({ model: Song, comparator: 'length' }),
    songCollection, song1, song2, song3;

song1 = new Song({ name: 'song1', length: 120 });
song2 = new Song({ name: 'song2', length: 90 });
song3 = new Song({ name: 'song3', length: 100 });

songCollection = new SongCollection();
songCollection.add([song1, song2, song3]);

Now if you examine the songCollection you will see the models are ordered by length from shortest to longest (song2, song3, song1) even though that is not the order they were added to the collection.

Note, you don't need to make all the models first then add them all at once. The collection will automatically sort itself anytime you add a new model.

The collection will fire a 'sort' event whenever it re-sorts. You can listen for this event to know when to update/redraw your views.

Collection -> comparator, sort

View -> event 'sort' -> render the whole collection or just update el's position in the DOM (using new model index in the collection). It's up to you. First is simplier but second should be much faster in case you have a lot of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM