1
votes

Question:

What is the lifecycle of the standard fetch method for a collection in Backbone? i.e. what events/methods are fired and in what order?

Context:

The JSON response I receive from the server for my collection has an array of models and a property:

{
    results: [model1, model2],
    aProperty: "example"
}

I would like to read this property from the JSON response and set it as a property on the Collection. I am currently overriding the parse function:

parse: function(response, options) {
    this.aProperty = response.aProperty;
    return response.results;
}

This feels like the wrong place to set properties in the collection - the parse function has a specific job and happens before the model array has been verified.

I have also tried:

initialize: function() {
    this.on('sync', function(collection, resp) {
        collection.aProperty = resp.aProperty;
    });
}

However, 'sync' is called after the success callback for a fetch (I need to set the properties as part of fetch, before the success callback).

1

1 Answers

0
votes

After reading the source code some, I think what you want to do is capture it on the request event. It is triggered on the model in Backbone.sync:

model.trigger('request', model, xhr, options);

Here you can override the callback sent as part of the request, wrapping it with the change you want to make. I didn't test this, but maybe this can give you an idea:

this.on('request', function(model, xhr, options) {
   var success;
   success = options.success;
   options.success = function(resp) {
        model.aProperty = resp.aProperty;
        success();
   }
});

Checkout out the annotated backbone source documentation. In particular the bit on Backbone.sync will help.