Thursday, March 27, 2014

Parsing Dates in Backbone Models

The parse() method on Backbone.Model is useful for parsing out using model properties. These are typically things like dates — the API doesn't return a JavaScript Date instance — it's either a number or a string representation of a date. That said, it's not terribly useful to store these strings or numbers in date properties of models. For example, using parse(), you can add a level of certainty in your application that the date fields on your models will always be Date instances, and not numbers or strings.

Something you want to avoid, however, when parsing model properties, is doing too much work. The last place you want to go digging when something strange starts happening in your views is the parse() method of some model. Simple manipulations do the job. I like to use the _.assign() Lodash function in my parse() methods because it's nice and simple. Here's the basic idea using date properties as an example.

var MyModel = Backbone.Model.extend({

    parse: function( response ) {
        return _.assign( response, {
            created: new Date( response.created ),
            modified: new Date( response.modified )


var MyCollection = Backbone.Collection.extend({

    model: MyModel,

    comparator: function( model ) {
        return -model.get( 'modified' );


You'll notice that the parse method is a quick one-liner, it's immediately obvious to the reader how the created and modified properties come about. The collection in the example can now reliably sort by date properties, since they've been consistently parsed into Date instances. You'll also notice that we're completely replacing the original data that's returned by the API. This I generally like to avoid doing, especially since it's the job of the template to present the data, even if it means transforming it on the fly.

The exception is made for dates, simply because the original representation from the API has no use to our model. Every aspect of our application relies on the date properties being Date instances, and in cases like this, it makes sense to replace the original data. Duplication is a possibility, stuffing the new form into another property, but that's generally a terrible idea because of the resulting confusion.

No comments :

Post a Comment