【发布时间】:2014-09-18 15:13:00
【问题描述】:
我对如何使用带有主干的 API 的 JSON 结构感到困惑。
我无法控制 api 的结构(它是来自 wordpress 插件 - woocommerce 的 REST api)。
我对 Backbone 的经验相对较少,我自己创建的每个 json api 都有以下结构:
[
{
"id": "1",
"name": "John",
"email": "john@example.com",
"order_number": "#3473388"
},
{
"id": "2",
"name": "Jane Doe",
"email": "jane@example.com",
"order_number": "#8877632"
}
]
对象数组,漂亮又简单!
但是, 我现在使用的 api 的结构具有以下结构:
{
"orders": [
{
"id": 130259,
"name": "John Doe",
"email": "john@example.com",
"order_number": "#3473388"
},
{
"id": 130259,
"name": "Jane Doe",
"email": "jane@example.com",
"order_number": "#3473388"
}
]
}
这是我的订单模型:
App.Models.Order = Backbone.Model.extend({
defaults: {
id: '',
name: '',
email: '',
order_number: ''
}
});
这是我的订单集:
App.Collections.Orders = Backbone.Collection.extend({
model: App.Models.Order,
url: 'http://api.example.com/orders'
});
我的模型/集合的结构和api没有很好的映射,当fetching我的集合时,返回了数据,但是不适合。如何使用骨干网来适应这种 json 结构?
更新
像这样覆盖集合上的 parse 方法(感谢 Yura)返回数据:
App.Collections.Orders = Backbone.Collection.extend({
model: App.Models.Order,
url: 'http://api.example.com/orders',
parse: function( resp ){
return resp.orders;
}
});
返回的数据是多维的,如下所示:
[
{
"id": 130285,
"order_number": "#130285",
"billing_address": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "13 Green Willow",
"address_2": "",
"city": "Celbridge",
"state": "Kildare",
"postcode": "",
"country": "IE",
"email": "johndoe@hotmail.com",
"phone": "87384348043"
}
}
]
在 parse 方法中,如何将多维 json 映射到我的集合的模型?
【问题讨论】:
-
您需要覆盖模型的
parse方法。
标签: javascript json backbone.js data-structures