问题描述
我已经用Tastypie-Django编写了一个API,我想使用Backbone做一个网页来更简单地访问模型。我在Backbone中创建了一个模型和类似的集合: var Abstract = Backbone.Model.extend({
默认值:{
}
});
var AbstractCollection = Backbone.Collection.extend({
model:Abstract,
url:http://192.168.0.195/api/v1/abstract/?format= json
});
查看中的fetch方法,如下所示:
var abs = new PocketsAbstractCollection();
abs.fetch({
success:function(collection,response){
console.log(abs.length);
console.log(abs.models);
}
});
这个问题是我从这个表单收到一个JSON:
{meta:{limit:20,next:null,offset:0,previous:null,total_count },objects:[{...}]}
当我看到属性中的集合我有2个元素,一个元和一个具有元素的对象数组。如何访问对象数组元素?
如果我写abs.attributes,这给我一个错误。
属性:对象
元:对象
对象:Array [12]
0:对象
1:对象
2:对象
3:对象
4:对象
。
。
。
长度:12
有人可以帮助我吗?
谢谢!!
Backbone希望收到一组对象。
Tastypie返回objects属性下的对象数组。
推荐的将Backbone想要的API响应的操作方式通过该集合的:
var AbstractCollection = Backbone.Collection.extend({
model:Abstract,
url:http ://192.168.0.195/api/v1/abstract/?format = json,
parse:function(response){
return response.objects;
}
});
您还可以使用Backbone-Tastypie'plugin':
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"
});
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);
}
});
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": [{ ... }]}
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?
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?
Thanks!!
Backbone expects to receive an array of objects.
Tastypie returns the array of objects under the "objects" property.
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;
}
});
You could also use Backbone-Tastypie 'plugin': https://github.com/PaulUithol/backbone-tastypie
这篇关于如何从Tastypie JSON访问骨干收集元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!