2013-02-13 17 views
7

コレクションによってフェッチされたモデルを反復しようとしています。collection.each()はモデルを反復処理しません

私は、コードの一部をfolowingています

initialize: function() { 
       this.collection = new UserCollection(); 
       this.collection.fetch(); 
       this.render(); 
      }, 

      renderCollection: function() { 
       console.log("rendering collection"); 
       this.collection.each(function(index,model){ 
        console.log("model"); 
       }); 
       console.log(this.collection); 
      }, 

render: function() { 
       this.template = _.template(template, {}); 
       this.$el.html(this.template); 
       // some other stuff 
       this.renderCollection(); 
} 

と結果:

rendering collection 

d {models: Array[0], length: 0, _byId: Object, constructor: function, model: function…} 
_byId: Object 
_idAttr: "id" 
length: 4 
models: Array[4] 
0: d 
_changing: false 
_events: Object 
_pending: false 
_previousAttributes: Object 
attributes: Object 
created: "2013-02-13 09:22:42" 
id: "1" 
modified: "2013-02-13 09:22:42" 
role: "admin" 
username: "[email protected]" 
__proto__: Object 
changed: Object 
cid: "c5" 
collection: d 
id: "1" 
__proto__: e 
1: d 
2: d 
3: d 
length: 4 
__proto__: Array[0] 
__proto__: e 
user_list.js:25 

だから、フェッチ方法は、仕事をした - オブジェクトのダンプに私がフェッチされた4つのレコードを見つけることができますが、コレクションを反復処理しうまくいきません...

答えて

8

提供された出力に基づいて、「モデル」が印刷されていないように見えます。おそらく、.each()ブロックが実行されたときに、this.collectionがまだ完全にフェッチされていない可能性があります。これは、JavaScriptの非同期性が原因です。

initialize: function() { 
    var me = this; 
    this.collection = new UserCollection(); 
    // Listen to 'reset' events from collection, so when .fetch() is completed and all 
    // ready to go, it'll trigger .render() automatically. 
    this.listenTo(this.collection, 'reset', this.render); 
    this.collection.fetch(); 
}, 

これを処理する他の方法は、フェッチに成功ハンドラを追加することですが、私はこのケースで十分なはずのイベントをリセットするために聞いて思う:

は、あなたのinitializeメソッドでこれを試してみてください。

希望すると便利です。

ところで、Cycloneによると、.eachのハンドラはインデックスのないモデルにすべきです。 :)

+1

jsonオブジェクトの有効な配列である必要があるサーバー出力から問題が発生する可能性があります。つまりPHPでインデックス付きのjson_encoded配列 –

+1

イテレータは次のいずれかでなければなりません。 'this.collection.each(function(model){...});' OR this.collection.each(function(model、index){...}); ' OPにインデックスがあり、モデルの向きが間違っています。 –

+0

私はこれ(コレクションではない)のようなcollection.modelsのそれぞれをやらなければなりませんでした:http://stackoverflow.com/questions/11726943/for-loop-over-backbone-collection...これは私の問題でした。 – Kelly

19

eachを収集すると、model自体がargumentとなります。

これを試してみてください:

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

それは、現在の反復のためにあなたにmodelを与える必要があります。

関連する問題