Most of my EmberJS projects use a datetime field somewhere on the backend. Reading them from the API is easy using a ‘date’ attribute type, but this doesn’t serialize to a very API friendly format. For example:
new Date().toString() "Wed Aug 06 2014 12:39:29 GMT+0200 (CEST)"
bower install --save moment
`import DS from 'ember-data'` IsodateTransform = DS.Transform.extend # The deserialize function just transforms the string it receives from the # server JSON response into a date. deserialize: (serialized) -> if serialized moment(serialized).toDate() # The serialize function takes the value of the attribute on the model and # transforms it into a nice ISO date to send to our server. serialize: (deserialized) -> if deserialized if deserialized instanceof Date moment(deserialized).toISOString() else # I'm using the European date format here. This is how date strings are # set on my models by my datetimepicker inputs. US readers may be able # to leave this second argument out moment(deserialized, 'DD/MM/YY h:mm a').toISOString() `export default IsodateTransform`
Now in any models where it is needed, you can use your isodate transform.
`import DS from 'ember-data'` User = DS.Model.extend createdAt: DS.attr('isodate') `export default User`
Need some extra development power?
I don't have a lot of time at the moment, but I'm always interested to hear about new projects. I'm particularly interested in EmberJS/Elixir projects and refactoring Rails monoliths. Drop me a line at hello [at] mattbeedle [dot] name or using my contact form http://www.mattbeedle.name/#page-contact.Tweet
comments powered by Disqus