In Backbone.js, I’m working with an API which wraps the response in a meta and data hash. For example:
# GET /api/posts/1
meta: {
status: 200
},
data: {
id: 1
title: 'Hello World'
}
# GET /api/posts
meta: {
status: 200
},
data: [
{
id: 1
title: 'Hello World'
},
{
id: 2
title: 'Hi everyone!'
}
]
My Backbone.js Collection/Models have the following parse function overwritten:
# App.Models.Post
...
parse: function (response) {
this.meta = response.meta;
return response.data;
}
# App.Collections.Posts
...
parse: function (response) {
this.meta = response.meta;
return response.data;
}
However, when I fetch on the collection posts = new App.Collections.Posts(); posts.fetch(), the post attributes are all empty. I.e. posts.at(0).get('title') = undefined.
Now, this is fixed when the Model parse is changed to:
parse: function (response) {
return response;
}
But this means that post.fetch() is broken.
Any suggestions?
Thanks!
I think the problem is that your model’s
parseis getting inconsistent data passed into it when done via modelfetchvs collectionfetch.console.logthe argument to modelparseto confirm this. This is because the value return by collection’sparseis just an array of object data and to convert those to models, the collection just delegates to the model’sparsemethod. This might fix your issue:For reference: https://github.com/documentcloud/backbone/pull/773