lundi 26 janvier 2015

Accessing DS.Transform objects from custom serializer

Im trying to figure out how could I invoke a transform instance from a custom transform class.


This is the idea:



App.TocEntrySerializer = Ember.Object.extend
serialize: (entry) ->
page: @_serializeAttribute 'page', 'number'
pagelabel: @_serializeAttribute 'pageLabel', 'string'
title: @_serializeAttribute 'title', 'string'
toc_entries: @_serializeAttribute 'tocEntries', 'tocEntries'

deserialize: (json) ->
Ember.Object.create
page: @_deserializeAttribute json['page'], 'number'
pageLabel: @_deserializeAttribute json['pagelabel'], 'string'
title: @_deserializeAttribute json['title'], 'string'
tocEntries: @_deserializeAttribute json['toc_entries'], 'tocEntries'

# Private

_serializeAttribute: (attribute, attributeType) ->
@_transformFor(attributeType).serialize attribute

_deserializeAttribute: (attribute, attributeType) ->
@_transformFor(attributeType).deserialize attribute

_transformFor: (attributeType) ->
@container.lookup "transform:#{attributeType}"


Im using this transform inside a model.



App.Ebook = DS.Model.extend
title: DS.attr('string')
tocEntries: DS.attr('tocEntries', {defaultValue: []})


And I'd like to be able to access to App.__container__ by using @container inside my custom serializer class. Note that Im not extending from DS.JSONSerializer or DS.RESTSerializer. This one is used inside my App.TocEntriesTransform class.



App.TocEntriesTransform = DS.Transform.extend
serialize: (deserialized) ->
deserialized.map (entry) =>
@get('_tocEntrySerializer').serialize entry

deserialize: (serialized) ->
serialized.map (jsonEntry) =>
@get('_tocEntrySerializer').deserialize jsonEntry

# Private

_tocEntrySerializer: ( ->
App.TocEntrySerializer.create()
).property()


I know I could invoke DS["#{type}Transform"] in order to obtain the needed class by its name, but I'd like to know if there is a better approach to take advantage of dependency injection in order to avoid internal dependencies.


Thanks in advance





Aucun commentaire:

Enregistrer un commentaire