Created
December 1, 2010 21:37
-
-
Save tbranyen/724272 to your computer and use it in GitHub Desktop.
handler code with render functionality added
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(window) { | |
// Required dojo template references | |
dojo.require("dojox.dtl"); | |
dojo.require("dojox.dtl.Context"); | |
window.renderTemplate = function() { | |
var template, context; | |
// Handle ajax requests | |
var ajax = function() { | |
// Create normalized xhr object | |
function xhr() { | |
// To stifile any exceptions | |
try { | |
// Detect native XMLHttpRequest object | |
if('XMLHttpRequest' in window && window.XMLHttpRequest) { | |
return new window.XMLHttpRequest(); | |
} | |
// Detect IE ActiveX object | |
if('ActiveXObject' in window && window.ActiveXObject) { | |
return new window.ActiveXObject("Microsoft.XMLHTTP"); | |
} | |
} | |
// Swallow exceptions and return undefined | |
catch(e) {} | |
} | |
// Cache to only create xhr function once | |
return function(path, callback) { | |
// Create new XHR instance | |
var _xhr = xhr(); | |
// Ensure XHR object exists | |
if(xhr) { | |
// Connect to server | |
_xhr.open("GET", path, true); | |
// Handle readyState and fresh / cached results | |
_xhr.onreadystatechange = function() { | |
if(_xhr.readyState === 4 && | |
_xhr.status === 200 || _xhr.status === 304) { | |
// Trigger the callback with the XHR object | |
callback(_xhr); | |
} | |
}; | |
// Initialize the request | |
_xhr.send(null); | |
} | |
}; | |
}(); | |
// If any ajax handlers fail then content will not be shown... | |
function render(node) { | |
// For this example use dojo's dtl template and context variables | |
var _template = new dojox.dtl.Template(template), | |
_context = new dojox.dtl.Context(context); | |
// Render | |
node.innerHTML = _template.render(_context); | |
} | |
// Container node to render template into and paths to template and context | |
return function(node, paths) { | |
// Fetch template markup | |
ajax(paths.template, function(xhr) { | |
template = xhr.responseText; | |
// Fetch the context object and parse into an Object | |
ajax(paths.context, function(xhr) { | |
context = JSON.parse(xhr.responseText); | |
// Template and handler have been set safe to render | |
template && context && render(node); | |
}); | |
}); | |
}; | |
}(); | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment