从服务器获取和呈现数据

我们需要定义一个带有 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(),
});