Backbone:访问集合模型

时间:2013-09-18 04:16:25

标签: javascript backbone.js

这个问题已被多次询问,但所提供的解决方案都不适用于我。

在这个Backbone集合中,我如何访问和循环其模型?

我在下面的代码中尝试了几种方法;包括基于Mark V.答案的补充。

此处也提供了代码:http://jsfiddle.net/LPbsP/3/

(function() {

console.log(Backbone);

window.App = {
    Model: {},
    Collection: {},
    View: {}
};

App.Model.Whatever = Backbone.Model.extend({});

App.Collection.Whatever = Backbone.Collection.extend({
    model: App.Model.Whatever,

    initialize: function(models, options) {
        this.getModels();

        _.bindAll(this, 'getModelsWithBindAll');
        this.getModelsWithBindAll();

        console.log(this);
        console.log(models);
        models.each(function(model) {
            console.log(model);
        });
    },

    getModels: function() {
        console.log('in getModels');
        console.log(this);

        whateverCollection.each(function(model) {
            console.log(model);
            console.log(model.toJSON());
        });
    },

    getModelsWithBindAll: function() {
        console.log('in getModelsWithBindAll');
        console.log(this);

        whateverCollection.each(function(model) {
            console.log(model);
            console.log(model.toJSON());
        });
    }
});

var whateverCollection = new App.Collection.Whatever([
    {
        name: 'jim',
        title: 'boss'
    },
    {
        name: 'tom',
        title: 'worker'
    }
]);

console.log('program code');
console.log(whateverCollection);

})();

结果:

Object (Backbone)

in getModels

r (length: 0, models: Array[0] ... )

Cannot call method 'each' of undefined

以下是我引用的其他问题:

1 个答案:

答案 0 :(得分:2)

有两种方法。

  1. 如果你需要在initialize方法中迭代它们,那么将initialize方法声明为initalize(模型,选项),因为Backbone将调用它。然后像在常规数组上一样遍历模型参数。这是因为在调用initialize时,this.models尚未填充模型。

  2. 如果您不需要在initialize方法中进行迭代,那么在定义了whateverCollection之后,只需执行:

     whateverCollection.each(function(model) {    
       console.log(model);    
       console.log(model.toJSON());    
     })