Reputation: 27
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!
Upvotes: 1
Views: 3804
Reputation: 146064
I think the problem is that your model's parse
is getting inconsistent data passed into it when done via model fetch
vs collection fetch
. console.log
the argument to model parse
to confirm this. This is because the value return by collection's parse
is just an array of object data and to convert those to models, the collection just delegates to the model's parse
method. This might fix your issue:
//App.Models.Post
parse: function (response) {
if (response.data) {
return response.data;
}
return response;
}
For reference: https://github.com/documentcloud/backbone/pull/773
Upvotes: 7