Last active
August 29, 2015 14:10
-
-
Save serverwentdown/9e4455100c43a8a2cb1c to your computer and use it in GitHub Desktop.
handlebars-autorenderer
This file contains hidden or 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 AutoRenderer() { | |
var parser = new DOMParser(); | |
this.handles = []; | |
this.context = {}; | |
function Handle(scriptElement, context) { | |
var templateString = scriptElement.innerHTML; | |
this.template = Handlebars.compile(templateString); | |
this.context = context || {}; | |
this.element = scriptElement; | |
} | |
Handle.prototype.update = function (newContext) { | |
newContext && (this.context = newContext); | |
var rawHTML = this.template(this.context); | |
var newElement = document.createElement("div"); | |
Array.prototype.forEach.call(parser.parseFromString(rawHTML, "text/html").firstChild.childNodes[1].childNodes, function (ele) { | |
newElement.appendChild(ele); | |
}); | |
this.element.parentElement.replaceChild(newElement, this.element); | |
this.element = newElement; | |
}; | |
var scriptElements = document.querySelectorAll("script[type='text/x-handlebars-template']"); | |
Array.prototype.forEach.call(scriptElements, function (scriptElement) { | |
var handler = new Handle(scriptElement, this.context); | |
this.handles.push(handler); | |
}.bind(this)); | |
} | |
AutoRenderer.prototype.update = function (newContext) { | |
for (var i = 0; i < this.handles.length; i++) { | |
var handle = this.handles[i]; | |
if (handle.context == this.context) { | |
handle.update(newContext); | |
} | |
} | |
this.context = newContext; | |
} |
Author
serverwentdown
commented
Dec 2, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment