Skip to content

Instantly share code, notes, and snippets.

@ivanvanderbyl
Last active September 23, 2016 15:16
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ivanvanderbyl/4553829 to your computer and use it in GitHub Desktop.
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
Copy link

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