主干:访问集合模型

Backbone: Access Collection Models

本文关键字:模型 集合 访问 主干      更新时间:2023-09-26

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

在此主干集合中,如何访问和循环遍历其模型?

我在下面的代码中尝试了几种方法;包括基于 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

以下是我提到的其他问题:

  • 尝试遍历主干中的集合以输出 DOM 中的属性

  • collection.each() 不迭代模型

  • 无法循环主干收集

  • 用于环路主干收集

有两种方法。

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

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

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