1
votes

I have an API that returns a collection of models, but it's not in the traditional format that Backbone expects - an array of models. Instead, there are some global properties to the collection, then the models are in an array assigned to a property of the collection. Something like this:

{
    foo: 'bar',
    models: [
        { id: 1, prop1: 'abc' },
        { id: 2, prop1: 'xyz' },
        { id: 3, prop1: '123' }
    ]
}

I can't change the API so I have to live with this data format. How do I massage the data so that the Backbone collection will get just the array of models? I've had a similar situation with a model and just wrote a custom toJSON() method which return the correct property with the model data, but that doesn't seem to work here.

1

1 Answers

2
votes

You need to override your collection's parse method, where you get the whole response object and you need return an array what Backbone will use to fill in your collection:

var MyCollection = Backbone.Collection.extend({
    parse: function(response) {
        return response.models;
    }
});