2011-08-31 15 views
37

私はBackboneで新しいです。だから私はRESTサービスからデータを取得しようとしています。Backbone.js + Rest。 fetch()の後でコレクションにデータが読み込まれない

これは私の単純なコードです:JSON次

$(function() { 

    var Entity = Backbone.Model.extend({ 
     url: function() { 
      return 'http://localhost:8080/rest/entity/'+this.id; 
     } 
    }); 

    var EntityList = Backbone.Collection.extend({  
     model: Entity, 
     url: 'http://localhost:8080/rest/entity' 
    }); 

    var entityList = new EntityList(); 

    entityList.fetch(); 

}); 

私の残りのサービスリターン:

デバッガで
[{"id":1387, 
    "version":3, 
    "entityName":"entity01", 
    "entityLabel":"Entity01", 
    "entityPluralLabel":"Entity01", 
    "attributes": 
    [{"id":1425, 
     "slot":"D001", 
     "version":0, 
     "attributeName":"dfield", 
     "attributeType": 
      {"id":7, 
      "description":"Date", 
      "attributeType":"date", 
      "databaseType":"DATE" 
      }, 
     "options":[], 
     "order":2, 
     "attributeLabel":"dField", 
     "checked":null 
     }, 
     {"id":1424, 
     "slot":"S001", 
     "version":0, 
     "attributeName":"txfield", 
     "attributeType": 
      {"id":1, 
      "description":"Textbox", 
      "attributeType":"textbox", 
      "databaseType":"STRING" 
      }, 
     "options":[], 
     "order":1, 
     "attributeLabel":"txField", 
     "checked":null 
     } 
    ] 
}, 
{"id":1426, 
    "version":3, 
    "entityName":"entity02", 
    "entityLabel":"Entity02", 
    "entityPluralLabel":"Entity02", 
    "attributes": 
    [{"id":1464, 
     "slot":"D001", 
     "version":0, 
     "attributeName":"dfield", 
     "attributeType": 
      {"id":7, 
      "description":"Date", 
      "attributeType":"date", 
      "databaseType":"DATE" 
      }, 
     "options":[], 
     "order":2, 
     "attributeLabel":"dField", 
     "checked":null 
     } 
    ] 
} 
] 

私はどのように私ができる、その要求はRESTサービスに送信し、応答を受け取ったとした参照entityListコレクションに受信データが設定されているかどうかを確認します。デバッガのentityList.modelsは、entityList.fetch()の後に空です。

私は正しい方法で、何かが私のコードで間違っていますか?

+1

バックボーンのソースコードは、このコードは、モデルのリストが空であることを言うだろうさ

ものすごく単純。たぶん、実際のバックボーンソースを踏んで、何が起こっているのかを知ることができます。 – Evert

答えて

83

あなたは正しい方法だと思います。しかし、Backbone.Collection.fetch()は非同期なので、メソッド呼び出しの直後ではないentityList.modelsの値をチェックする必要がありますが、フェッチのコールバックはsuccessです。

entityList.fetch(); 
console.log(entityList.models); // => 0 (collection being fetched) 

それが取り込まれていたときに、このコードは、コレクション内のモデルの数を印刷する一方:

entityList.fetch({success: function(){ 
    console.log(entityList.models); // => 2 (collection have been populated) 
}}); 
+6

さらに、コレクションの 'parse'関数のオーバーロードを検討してください。それが到着したときの応答を見ることができます。そして、私はしばしば、その時にオブジェクトに値を設定する以上のことをしたいと思っています。あなたの答えは – idbentley

+1

ありがとう。あなたは非同期フェッチについて正しいです、私はデバッグ中にこれを突然見つけました:) – Danyan

+0

これは私に数時間のトラブルシューティングを保存しました。私はフェッチした直後にコレクションを使いたいと思っていましたが、それは空でした。フェッチする成功ハンドラを追加すると、コレクションに正しく挿入されました。ありがとう! – Hcabnettek

関連する問題