Last active
August 29, 2015 13:57
-
-
Save Schniz/9559139 to your computer and use it in GitHub Desktop.
momentjs + ember = {{timeago}} helper!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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