Created
October 19, 2012 18:02
-
-
Save jmorton/3919665 to your computer and use it in GitHub Desktop.
Augment yer DOM with Augmenter
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
/** | |
* Usage: | |
* | |
* <script src="augmenter.js" type="text/javascript"></script> | |
* <script> | |
* new Augmenter({ attr: 'data-employee', url: '/employee?id=' }) | |
* </script> | |
* | |
* Any elements like this in your document: | |
* | |
* <div data-employee="1234">Me</div> | |
* | |
* ...will be updated with whatever document is returned by the construced | |
* URL. In my case, that is something like: | |
* | |
* <div class="vcard"> | |
* <img class="photo" src="http://example.com/public/employees/1234/avatar.jpg"> | |
* <span class="fn">Jonathan Morton</span> | |
* <div class="title">Software Engineer</div> | |
* <div class="org">Technology</div> | |
* <div class="adr"> | |
* <span class="locality">McLean</span> | |
* <span class="region">Virginia</span> | |
* </div> | |
* </div> | |
* | |
*/ | |
var Augmenter = function(cfg) { | |
var match = function(el) { | |
return el.querySelectorAll('[' + cfg.attr + ']'); | |
}; | |
var id = function(el) { | |
return el.getAttribute(cfg.attr); | |
}; | |
var urlize = function(id) { | |
return cfg.url+id; | |
}; | |
var identify = function(root) { | |
var el, els = match(root); | |
for (var i = 0; i < els.length; i++) { | |
el = els[i]; | |
fetch(id(el),augment(el)); | |
}; | |
}; | |
var fetch = function(id, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', urlize(id),true); | |
xhr.setRequestHeader('Accept','text/html'); | |
xhr.send(); | |
xhr.onload = callback; | |
}; | |
var augment = function(element) { | |
return function(evt) { | |
var response = evt.target.response; | |
element.innerHTML = response; | |
}; | |
}; | |
document.addEventListener("DOMContentLoaded", function() { | |
console.debug("Eager loading on DOMContentLoaded."); | |
identify(document); | |
}, false); | |
document.addEventListener("DOMNodeInserted", function(evt) { | |
console.debug("Eager loading on DOMNodeInserted."); | |
var el = evt.target; | |
if ((el instanceof Element)) { | |
identify(el); | |
} | |
}, false); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment