A simple Handlebars helper to do automatically updating dates. Requires moment.js
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
(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); | |
}) | |
}); | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bugs: 30&40th line
if (this.updateTimer) { clearTimeout(this.updateTimer) };
should beif (this.updateTimer) { clearTimeout(this.updateTimer); }
and 54th line misses a semicolon;
.