【问题标题】:Backbone: Access Collection Models主干:访问集合模型
【发布时间】:2026-01-22 16:30:02
【问题描述】:

这个问题已经被问过好几次了,但是提供的解决方案都不适合我。

在这个 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

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

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    有两种方法。

    1. 如果您需要在初始化方法中对它们进行迭代,则将您的初始化方法声明为 initalize(models, options),因为 Backbone 会这样调用它。然后像遍历常规数组一样遍历模型参数。这是因为 this.models 在调用 initialize 时还没有填充模型。

    2. 如果您不需要在初始化方法中进行迭代,那么在定义您的whateverCollection 之后,只需执行以下操作:

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

    【讨论】:

    • 感谢您的回复-您能看一下这个小提琴吗:jsfiddle.net/LPbsP/2?我仍然无法让 initialize() 等待集合传入。
    • 我更新了问题以包含小提琴代码,所以你可以参考上面 - 再次感谢