Question

im learning BackboneJs using the documentation and a book called "Beginning backbone". But I have been stuck at the sorting collections part for hours. Also tried to research but I find the results complicated =/

I know I have to use the comparator, as shown in the documentation but I don't understand how to apply it to the current code syntax-wise

http://backbonejs.org/#Collection-comparator

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 20
    },
    comparator: function(item)
    {
        //sort by title
        return item.get('title');   
    }
});

var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});

var Library = Backbone.Collection.extend({
    model: Book
});

var library = new Library([book1,book2]);
library.add([book3,book4]); 

library.forEach(function(model){
    console.log('Book is called '+model.get("title"));
});

console.log('Library contains '+library.length+' books');
Was it helpful?

Solution

This is a working solution, it will sort everything by title. to sort it by anything else just change the parameter of the get function inside the comparator function

    var Book = Backbone.Model.extend({
        defaults:
        {
            title: "default title",
            author: "default author",
            pages: 20
        } 
    });

    var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
    var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
    var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
    var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});

    var Library = Backbone.Collection.extend({
        model: Book,
        initialize: function()
        {
            console.log("new collection");
        },
        comparator: function(a,b)
        {
            //sort by title
            return a.get('title') < b.get('title') ? -1 : 1;
        }
    });

    var library = new Library([book1,book2]);
    library.add([book3,book4]); 

    library.sort(); 
    library.forEach(function(model){
        console.log('Book is called '+model.get("title"));
    });

    console.log('Library contains '+library.length+' books');   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top