this.collection.each不迭代

时间:2013-06-15 16:45:49

标签: javascript backbone.js

我正在尝试了解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();

1 个答案:

答案 0 :(得分: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});