问题
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!!
回答1:
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
来源:https://stackoverflow.com/questions/12623284/how-i-acces-to-backbone-collection-elements-from-tastypie-json