Custom Transforms in Ember Data Rev 6

October 18, 2012 Dwayne Forde

Ember Data is a library for loading models from a persistence layer (such as a JSON API), updating those models, then saving the changes. It provides many of the facilities you’d find in server-side ORMs like ActiveRecord, but is designed specifically for the unique environment of JavaScript in the browser.

When I was working in Rev 4 of Ember Data I found this handy article which explained a handy way of adding custom transforms. This way, I don’t need to create an Ember model to parse objects in my JSON that don’t represent models in my Rails application.

When I upgraded to Rev 6, I noticed this code broke. After digging through the documentation I discovered that an API for registering new transforms was implemented.

The way of adding a new transform changed from this:

DS.attr.transforms.object = {
  from: function(serialized) {
    return Em.none(serialized) ? {} : serialized;
  },
  to: function(deserialized) {
    return Em.none(deserialized) ? {} : deserialized;
  }
}

to this:

DS.RESTAdapter.registerTransform('object', {
  fromJSON: function(serialized) {
    return Em.none(serialized) ? {} : serialized;
  },
  toJSON: function(deserialized) {
    return Em.none(deserialized) ? {} : deserialized;
  }
})

A simple code change but it’s nice to have an API to register new transforms. Hopefully there are more Ember Data goodness to come as it matures towards a 1.0 release.

About the Author

Biography

More Content by Dwayne Forde
Previous
Spike Driven Design
Spike Driven Design

I'm really excited about a collection of new techniques I've been experimenting with over the past few week...

Next
what, CI Reporter?
what, CI Reporter?

Helps iPad/iOS - full page redraws iOS devices do a full-page redraw when we introduce new height at the b...

Enter curious. Exit smarter.

Register Now