Skip to content

Instantly share code, notes, and snippets.

@Schniz
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Schniz/9559139 to your computer and use it in GitHub Desktop.
Save Schniz/9559139 to your computer and use it in GitHub Desktop.
momentjs + ember = {{timeago}} helper!
// ember-timeago.js
// Using momentjs to provide neat helper for fromNow() calls.
App.Clock = Em.Object.create({
seconds: 0,
minutes: 0,
hours: 0,
init: function() {
this.tick();
},
tick: function() {
var date = new Date;
this.set('seconds', date.getSeconds());
this.set('minutes', date.getMinutes());
this.set('hours', date.getHours());
var clock = this;
setTimeout(function() {
clock.tick();
}, 1000);
}
});
// Usage: {{timeago time=YOUR_DATETIME_OBJECT_HERE}} => "3 seconds ago". HORRAY!!!
App.TimeAgoView = Em.View.extend({
tagName: 'time',
template: Ember.Handlebars.compile('{{ view.fromNow }}'),
secondsBinding: 'App.Clock.seconds',
value: '',
fromNow: function() {
// Call momentjs once in 10 seconds.
if (this.get('value') === '' || this.get('seconds') % 10 === 0) {
this.set('value', moment(this.get('time')).fromNow());
}
return this.get('value');
}.property('seconds')
});
Ember.Handlebars.helper('timeago', App.TimeAgoView);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment