0

この質問は何度か聞かれましたが、提供された解決策はどれもうまくいきません。

このバックボーン コレクションでは、モデルにアクセスしてループするにはどうすればよいですか?

以下のコードでいくつかの方法を試しました。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

私が参照した他の質問は次のとおりです。

4

1 に答える 1

2

2 つの方法があります。

  1. 初期化メソッドでそれらを反復する必要がある場合は、初期化メソッドを initalize(models, options) として宣言します。これは、バックボーンがそれを呼び出す方法です。次に、通常の配列に対して行うように、models パラメーターを反復処理します。これは、initialize が呼び出された時点で this.models にモデルが入力されていないためです。

  2. initialize メソッドで繰り返す必要がない場合は、whateverCollection を定義した後、次のようにします。

     whateverCollection.each(function(model) {    
       console.log(model);    
       console.log(model.toJSON());    
     })    
    
于 2013-09-18T04:43:38.453 に答える