【问题标题】:Backbone collection.fetch(), parse doesn't work骨干collection.fetch(),解析不起作用
【发布时间】:2013-03-13 11:38:49
【问题描述】:

我正在使用backbone.js,我想从服务器获取我的集合的数据:

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() 返回空数组 ([ ])。 请帮我看看代码有什么问题。

【问题讨论】:

  • 这是一个常见问题——获取与documented 是异步的。您需要在调用中添加success 回调以获取,或连接到集合的重置/添加事件之一。
  • 还要注意应该是var accountList = new AccountList();

标签: javascript backbone.js


【解决方案1】:

因此,正如 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.

【讨论】:

    猜你喜欢
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2012-12-02
    • 2015-05-11
    相关资源
    最近更新 更多