Reputation: 115
I am returning JSON data from a remote server which holds some information. (The product name and the date).
I want to modify the date output in my handlebars template. Here is a JSBin with my code.
Should I use a property in order to change the format of the date? Or there is a better way to do that? If yes, what should I do?
Thank you in advance.
Upvotes: 1
Views: 57
Reputation: 21511
The better way to do it is to use an Handlebars Helper to convert your date into a useable format. The reason a helper is better than a computed property, is it can be reused throughout your code anywhere you need to format a date in the template.
I have updated the JSBin to use this helper.
Ember.Handlebars.helper('dateformat', function(value) {
// Use moment, or alternatively use JavaScript date and return your own custom string
return moment(value).format("DD/MM/YY"); // Change to suitable format. See http://momentjs.com/docs/
});
{{dateformat item.date}}
This example uses the MomentJS library to convert the date into format DD/MM/YY
but obviously you can change this.
It is possible to do the conversion without using this external library, using the standard JavaScript date
object. The helper just needs to return the formatted string.
To do it as a computed property requires a little more effort. You can see a working demo of this here. The demo uses a modified version of your localeDate
function.
So create a HistoryItem
object that has the computed property.
App.HistoryItem = Ember.Object.extend({
localeDate: function() {
var dt = new Date(this.get('date'));
return dt.toLocaleDateString() + " " + dt.toLocaleTimeString();
}.property('date')
});
The model is a plain object, you need to create an instance of the HistoryItem
for each item in your history.
App.IndexRoute = Ember.Route.extend({
model: function() {
// Get the history
var history = App.JsonRequestFromRemoteServer.history;
var result = [];
// Create item as history item
history.forEach(function(item){
result.push(App.HistoryItem.create(item));
});
// Return the result as the model
return { history: result };
}
});
Hope this helps.
To address why your JSBin here didn't work:
You were trying to use property("[email protected]")
, to create a computed property on each item in the collection.
Unfortunately what this does is provide what's called an Aggregated Property. You can read more about aggregated properties here, but essentially that would give you one property on your history object based on all the dates in the collection. Not a single property on each item as desired.
I do think this is an area of Ember that should be better covered in the documentation, you're not the first person to think you can add computed properties to collections that way.
Upvotes: 2