Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Handlebars helper to do automatically updating dates. Requires moment.js
<time>{{timeAgoInWords post.publishedAt}}</time>
(function() {
Ember.Handlebars.registerHelper('timeAgoInWords', function(property, options) {
var data = options.data,
view = data.view,
currentContext = (options.contexts && options.contexts[0]) || this,
pathRoot, path, normalized;
normalized = Ember.Handlebars.normalizePath(currentContext, property, data);
pathRoot = normalized.root;
path = normalized.path;
var bindView = new Ember._SimpleHandlebarsView(
path, pathRoot, !options.hash.unescaped, options.data
);
bindView.normalizedValue = function() {
var value = Ember._SimpleHandlebarsView.prototype.normalizedValue.call(bindView);
return function(value, options) {
// This returns the value to actually render.
return moment(value).fromNow(false);
}.call(view, value, options);
};
view.reopen({
didInsertElement: function() {
var self = this;
if (this.updateTimer) { clearTimeout(this.updateTimer) };
this.updateTimer = setInterval(function() {
if (self.state === 'inDOM') {
Ember.run.scheduleOnce('render', bindView, 'rerender');
}
}, 10000);
},
willDestroyElement: function() {
if (this.updateTimer) { clearTimeout(this.updateTimer) };
}
});
view.appendChild(bindView);
observer = function() {
Ember.run.scheduleOnce('render', bindView, 'rerender');
};
Ember.addObserver(pathRoot, path, observer);
view.one('willClearRender', function() {
Ember.removeObserver(pathRoot, path, observer);
})
});
})()
@changeweb

This comment has been minimized.

Copy link

changeweb commented Dec 9, 2014

Bugs: 30&40th line if (this.updateTimer) { clearTimeout(this.updateTimer) }; should be if (this.updateTimer) { clearTimeout(this.updateTimer); } and 54th line misses a semicolon ;.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.