Created
December 1, 2010 21:21
-
-
Save tbranyen/724250 to your computer and use it in GitHub Desktop.
handler file with ajax functionality added in
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) { | |
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); | |
} | |
}; | |
}(); | |
// 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(); | |
}); | |
}); | |
}; | |
// Render block | |
}(); | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment