1

我正在尝试了解 Backbone 并尝试创建一些小的 REST API 前端,但无法开始View工作。

fetch()返回三个元素的有效 JSON 数组。并且this.collection.models不是空的(typeof object- []) - 它有树子对象元素。但是each迭代不会触发。

当检查 collection.models 是否存在时console.log(this.collection.models);,看起来一切正常:

console.log(this.collection.models)

如果有任何建议,我将不胜感激!

var Account = Backbone.Model.extend({});

var AccountsCollection = Backbone.Collection.extend({
    model: Account,
    url: 'api/v1/accounts',
    initialize: function () {
        this.fetch();
    }
});

var AccountsView = Backbone.View.extend({
    render: function() {

        // Check if there is something
        console.log(this.collection.models);

        // This doesn't work
        _.each(this.collection.models, function(model) {
            console.log(model);
        });

        // Neither this
        this.collection.each(function(model) {
            console.log(model);
        });
    }
});


var a = new AccountsView({collection: new AccountsCollection()});
a.render();
4

1 回答 1

4

第一个选项

var AccountsCollection = Backbone.Collection.extend({
    model: Account,
    url: 'api/v1/accounts'
});

var AccountsView = Backbone.View.extend({
    render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

collection.fetch().done(function () {
    // collection has been fetched
    view.render();
});

第二种选择

var AccountsCollection = Backbone.Collection.extend({
    model: Account,
    url: 'api/v1/accounts'
});

var AccountsView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.collection, 'sync', this.render);
    },
    render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

第三个选项

var AccountsCollection = Backbone.Collection.extend({
    model: Account,
    url: 'api/v1/accounts',
    initialize: function () {
        this.deferred = this.fetch();
    }
});

var AccountsView = Backbone.View.extend({
    initialize: function() {
        this.collection.deferred.done(_.bind(this.render, this));
    },
    render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});
于 2013-06-15T17:57:10.723 回答