從伺服器獲取和呈現資料

我們需要定義一個帶有 url 屬性的集合。這是 API 端點的 url,它應該返回一個 json 格式的陣列。

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

然後,在檢視中,我們將非同步獲取和呈現:

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
    },
});

使用此檢視的最簡單方法:

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