Tuesday, August 07, 2012

Backbone: When does Parse happen?

Backbone calls parse on your models at the moment of initialization by an AJAX request, typically in JSON format.

Parse sounds like a great point to override for custom deserialization, but what about when you are bootstrapping the Models via JSON dumped into the page?  Turns out you can do it then too -- optionally.

When does parse get called?

Model & Collection Initialize: No, Optional

The docs don't show it, but Model is like Collection in that it accepts a second argument of options.  You can pass in {parse: true} in the options of both Model and Collection initializers and then parse will be called.

Model Fetch & Save: Yes, Always

All fetch and save operations on Models always call parse.  The save passes it through to it's success callback.

Collection Fetch: Yes, Overrideable

Collection fetch is interesting because it will call it's own Collection parse within the success callback.  To be clear, this means you have an implementation of 'parse' on your Collection not your Model.

In addition, it has a callback to the Model parse which is overrideable on the fetch options.

Summary

Model#initializeOptional when {parse: true}
Collection#initializeOptional when {parse: true}. Will call Model.parse via #reset
Model#fetchModel.parse on internal success callback
Model#saveModel.parse on internal success callback
Collection#fetchCollection.parse on internal success callback
Model.parse on add/reset call per model (overrideable)

No comments: