Ember Data Custom Transforms

I'm relatively new to both EmberJS and Ember Data, however picking it up and using it to build an app from scratch has been both a really rewarding experience and a breeze. However, a few days back, I stumbled upon a minor hiccup while working on a feature.

The problem

The API from which data is being sent to the Ember App provides information in the following manner via JSON.

{
  "id": "xxx",
  "name": "xxx",
  "views": [
    "viewA": {...},
    "viewB": {...},
    "viewC": {...}
  ]
}

While the name attribute can easily handled by the use of Ember Data string attribute, views requires special consideration.

Essentially the views attribute is an array of objects containing their own relevant information. If the views had their own unique identifiers and were being persisted in a database, it would have been really easy to to just utilize Ember Data relationships.

Unfortunately the data is fetched from another API and is of a nature that for which it doesn't make much sense to store locally.

Custom Transformations to the rescue

I decided on using Custom transformations that are explained pretty well in the documentation.

Portal.ArrayObjectTransform = DS.Transform.extend  
  deserialize: (serialized) ->
    type = Ember.typeOf(serialized)

    if type == 'array'
      data = []
      for attr in serialized
        data.pushObject(Ember.Object.create(attr))
      return data
    else
      return serialized

  serialize: (deserialized) ->
    return deserialized

I created Ember Objects from the JSON data and pushed them into an array. The reason for creating Ember Objects is so that I could utilize features such as bindings on the attributes for the view objects.

Now that my new attribute is defined, I can use it to define a model.

Portal.RandomModel = DS.Model.extend(  
  name:      DS.attr 'string'
  views:     DS.attr 'arrayObject'
)

Warning

I read on public threads that developers were facing certain issues with their models that utilize custom attributes, such as records incorrectly identifying themselves as not being dirty(which in turn affects updating records). Hacks such as utilizing a lastUpdated atribute that is bumped to the current time before invoking the save method on the record seem to resolve this issue.

Fortunately for me(I'm not sure why, perhaps I'm on a different version) I did not face any issues and things have been working fine.

comments powered by Disqus