2013-03-13 75 views
2

我使用Backbone.js的工作和我想从服务器获取我的收藏数据:骨干collection.fetch(),解析不

var Account = Backbone.Model.extend(); 
var AccountList = Backbone.Collection.extend({ 
     model: Account, 

     url: '/pfp/accounts/service', 

     parse: function(response){ 
      return response.Data; 
     } 

    }); 
var accountList = new AccountList; 
accountList.fetch(); 
console.log(accountList.toJSON()); 

服务器响应:

{"Data": 
[{"accountid":"101752","account_name":"hijklmnopq","userid":"1","comment":"mnopqrstu","creation_date":"6 Jan 2008","account_type":"2","acc_type_name":"Дебетовая карта","currency":"144","letter_code":"","start_balance":"90.000.000","start_balance_raw":90000000.000,"to_total":true}, 
{"accountid":"144924","account_name":"emabcefghijklmnopqr","userid":"1","comment":"lmno","creation_date":"19 Jan 2008","account_type":"4","acc_type_name":"Банковский счёт","currency":"113","letter_code":"Le","start_balance":"360.000.000,00","start_balance_raw":360000000.000,"to_total":true}, 
... 

accountList.toJSON()返回空数组([])。 请帮我看看代码出了什么问题。

+2

这是一个共同的问题 - 获取是异步的[记录](HTTP:/ /backbonejs.org/#Collection-fetch)。您需要在调用中添加“成功”回调以获取或连接到集合的重置/添加事件之一。 – WiredPrairie 2013-03-13 12:04:23

+0

http://stackoverflow.com/questions/7259712/backbone-js-rest-collection-is-not-populated-after-fetch – WiredPrairie 2013-03-13 12:06:28

+0

另外请注意,应该是'var accountList = new AccountList();' – sQVe 2013-03-13 12:15:24

回答

4

所以,WiredPrairie说,你需要改变这些行:

accountList.fetch(); 
console.log(accountList.toJSON()); 

到:

accountList.fetch({ 
    success: function(collection){ 
    // This code block will be triggered only after receiving the data. 
    console.log(collection.toJSON()); 
    } 
}); 
// JS will likely reach this line before receiving the data. 
+0

谢谢你的回复! – Margarita 2013-03-13 13:15:03