我如何查看在Tastypie JSON骨干收集要素? [英] How I acces to Backbone collection elements from Tastypie JSON?
问题描述
我已经写有Tastypie,Django的一个API和我想做的使用骨干做的更简单地进入到模型的网页。我创建了一个骨干模型和集合是这样的:
I've write a API with Tastypie-Django and I want to do a webpage using Backbone to do more simply access to model. I've created a Model and a collection like this in Backbone:
var Abstract = Backbone.Model.extend({
defaults : {
}
});
var AbstractCollection = Backbone.Collection.extend({
model: Abstract,
url : "http://192.168.0.195/api/v1/abstract/?format=json"
});
该fetch方法是在视图威腾是这样的:
The fetch method it's witten in the View and it's like this:
var abs = new PocketsAbstractCollection();
abs.fetch({
success: function (collection, response) {
console.log(abs.length);
console.log(abs.models);
}
});
问题是,我收到一个JSON从这种形式:
The problem it's that I receive a JSON from this form:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 12}, "objects": [{ ... }]}
,当我看到在属性集合的模式,我有2个元素,元和元素的对象数组。我怎样才能访问对象元素的数组?
and when I see the model of the collection in attributes I have 2 elements, a Meta and a Objects Array with the elements. How can I access to the Array of Objects elements?
如果我写这abs.attributes给我一个错误。
If I write abs.attributes this give me an error.
attributes: Object
meta: Object
objects: Array[12]
0: Object
1: Object
2: Object
3: Object
4: Object
.
.
.
length: 12
有人能帮助我吗?
Can someone help me?
谢谢!
推荐答案
骨干期望接收对象的数组。
Backbone expects to receive an array of objects.
Tastypie返回下的对象属性的对象的数组。
Tastypie returns the array of objects under the "objects" property.
操纵API响应为骨干想要的格式的推荐方法是通过收集的 解析
功能:
The recommended way of manipulating API responses into the format Backbone wants is through the collection's parse
function:
var AbstractCollection = Backbone.Collection.extend({
model: Abstract,
url : "http://192.168.0.195/api/v1/abstract/?format=json",
parse: function(response) {
return response.objects;
}
});
您也可以使用骨干-Tastypie'插件':<一href=\"https://github.com/PaulUithol/backbone-tastypie\">https://github.com/PaulUithol/backbone-tastypie
You could also use Backbone-Tastypie 'plugin': https://github.com/PaulUithol/backbone-tastypie
这篇关于我如何查看在Tastypie JSON骨干收集要素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!