Syed Ali
Syed Ali

Reputation: 1897

How to load backbone model from an attribute in response?

I am having trouble in binding an odata response to my model. Initially I had a simple model and a simple response which is working fine. But then I changed my response to be in odata format. My backbone modle is:

    var UserCard = Backbone.Model.extend({
    defaults: {
        ...
    }
});

and its related collection:

    var UserCards = Backbone.Collection.extend({
    model: UserCard,
    url: '/odata/UserCards'
});

now this collection was being populated until I changed the response which now looks like below:

{
 "odata.metadata":"http://website.com:53176/odata/$metadata#UserCards",
 "value":[{...},{...}...]
 }

When I call the collection.fetch method it tries to put the above in my model which is not compatible with this response. The model however is compatible with whatever is contained inside the value attribute of the above json.

I would like to find out if there is a way I can load my model from the value attribute instead of the full response?

Upvotes: 0

Views: 90

Answers (1)

Twicetimes
Twicetimes

Reputation: 678

You can override the parse() method for your model/collection. eg:

parse: function(data) {
    return data.value;
}

parse is the method Backbone calls when it retrieves data from the server, see Backbone docs here

Upvotes: 2

Related Questions