backbone.js Collection Fetching and rendering data from the server


Example

We need to define a collection with a url property. This is the url to an API endpoint which should return a json formatted array.

var Books = Backbone.Collection.extend({
    url: "/api/book",
    comparator: "title",
});

Then, within a view, we'll fetch and render asynchronously:

var LibraryView = Backbone.View.extend({
    // simple underscore template, you could use 
    // whatever you like (mustache, handlebar, etc.)
    template: _.template("<p><%= title %></p>"),

    initialize: function(options) {
        this.collection.fetch({
            context: this,
            success: this.render,
            error: this.onError
        });
    },

    // Remember that "render" should be idempotent.
    render: function() {
        this.$el.empty();
        this.addAll();

        // Always return "this" inside render to chain calls.
        return this;
    },

    addAll: function() {
        this.collection.each(this.addOne, this);
    },

    addOne: function(model) {
        this.$el.append(this.template(model.toJSON()));
    },

    onError: function(collection, response, options) {
        // handle errors however you want
    },
});

Simplest way to use this view:

var myLibrary = new LibraryView({
    el: "body",
    collection: new Books(),
});