Question

I'm using custom parse() methods on both my base collection and base model to handle all the wrapping that my server returns around them.

My problem is that the collection calls parse() on every model too which is not needed, i only need to parse on the model when fetching from the model instead of the collection.

Should i change fetch in some way or is there any other option? I found some comments about a parse = true option but no real documentation on that.

// Base class for all models
module.exports = Backbone.Model.extend({
    parse: function(response) {
        var retrocycled = JSON.retrocycle(JSON.parse(JSON.stringify(response)));
        this.statusResp = retrocycled.status;
        this.messageResp = retrocycled.message;
        return retrocycled.data;
    }
});

My collection does roughly the same in it's parse, but it doesn't really matter what it does, i just need them to only parse when they were the ones fetching i guess.

Thanks!

Was it helpful?

Solution

If you look at the Backbone source code line 256 specifically you'll see that parse is called, if it exists, when creating a new Model.

When you add models to a collection, it takes the response from the server, and for each item in it, it just generates a new model with that data.

However, the collection itself has a parse method as well that gets called.

But what you're looking for is a conditional call to Model#parse depending on the context. The issue here is that when the Model is being created it doesn't know if you're doing it as a standalone model or as part of the context of creating a collection.

You'd have to design your model parse method to introspect response and determine if it needs extra processing or not. If not, just return response back out. If so, do your work, and then return the "fixed" response.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top