I'm trying to use Backbone with an API.
The default API response format is:
{ somemetadatas:xxx , results:yyy }
Whether it's a fetch for a single model or a collection.
So as far as I know I can override the Backbone parse
function with:
parse: function (response) { return response.results; },
But I've seen in the documentation:
parse
collection.parse(response)
parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw
response
object, and should return the array of model attributes to be added to the collection. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses. Note that afterwards, if your model class already has aparse
function, it will be run against each fetched model.
So if I have a response for a collection fetch like that:
{ somemetadatas:xxx , results:[user1,user2] }
The first parse
function on the collection will extract [user1,user2]
.
But the doc says:
Note that afterwards, if your model class already has a
parse
function, it will be run against each fetched model.
So it will try to find response.results;
on user1
and user2
I need both parse functions on the model and collection because both model and collection datas will be under the result attribute.
But if i fetch on a collection, I don't want the model parse function to be used againt a single array element.
So is there a solution to this problem?
I think of a solution where my collection parse function will transform something like this:
{ somemetadatas:xxx , results:[user1,user2] }
into something like this:
[ {results.user1} , {results.user2} ]
So that the model parse function will not fail on a collection fetch. But it's a bit hacky... is there any elegant solution to this problem?
By the way, as my API will always produce results of this form, is it possible to override by default the parse
function of all my models and collections? (Sorry i'm a JS noob...)
You could test if the data you receive is wrapped by a results
member and react accordingly. For example,
var M = Backbone.Model.extend({ parse: function (data) { if (_.isObject(data.results)) { return data.results; } else { return data; } } });
And a Fiddle http://jsfiddle.net/9rCH3/
If you want to generalize this behavior, either derive all your model classes from this base class or modify Backbone's prototype to provide this function :
Backbone.Model.prototype.parse = function (data) { if (_.isObject(data.results)) { return data.results; } else { return data; } };
http://jsfiddle.net/9rCH3/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With