Reputation: 569
I decided to use UTC dates in my Ember app so by following the recommendation here I created the following transform:
app/transforms/utc.js
import DS from "ember-data";
export default DS.Transform.extend({
serialize: function(value) {
return value ? value.toJSON() : null;
},
deserialize: function(value) {
return moment.utc(value);
}
});
I then used it in my model:
app/models/payment.js
import DS from 'ember-data';
export default DS.Model.extend({
student: DS.belongsTo('student'),
date: DS.attr('utc'),
amount: DS.attr('number'),
formattedDate: function() {
var date = this.get('date');
return moment(date).format("DD/MM/YYYY");
}.property('date')
});
Before using the utc
transform I was able to sort the payments by using this function:
payments: (function() {
return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
sortProperties: ['date'],
sortAscending: false,
content: this.get('content.payments')
});
}).property('content.payments'),
Now, after using the utc
transform, the above function doesn't work anymore. Any idea why?
Upvotes: 0
Views: 173
Reputation: 37379
I believe it's because moment doesn't give you date objects, it gives you a special moment object. Normally, this wouldn't matter since moment gives those objects a valueOf
method which will satisfy the built-in Javascript comparison operators. Ember, however, uses a custom sort function. Looking at the source code for Ember.compare, we can see that there's a specific path for Javascript date objects, but for normal Javascript objects it always returns 0 (sorted equally).
Long story short, use a compare function instead of the compare property name (using the built-in Javascript comparison operators):
sortFunction: function(a, b) {
return (a < b ? -1 : 1);
}
Upvotes: 1