Skip to content

Instantly share code, notes, and snippets.

@kobachi
Last active August 29, 2015 13:57
Show Gist options
  • Save kobachi/9755518 to your computer and use it in GitHub Desktop.
Save kobachi/9755518 to your computer and use it in GitHub Desktop.
Automated Action Binding for JavaScript
window.ActionBinder = new (function(){
function getObject(path){
var p = path.split(".");
var o = window;
for(var i = 0; i < p.length; i++){
if(typeof o[p[i]] == "undefined"){
return null;
}
o = o[p[i]];
}
return o;
}
function bind(){
Array.prototype.forEach.call(document.querySelectorAll("[data-js-action]"), function(e){
e.addEventListener("click", function(){
var f = getObject(this.getAttribute("data-js-action"));
if(typeof f == "function"){
f.apply(this);
}
else{
alert(this.getAttribute("data-js-action") + " is not a function.");
}
});
});
}
this.bind = bind;
});
@kobachi
Copy link
Author

kobachi commented Mar 25, 2014

usage:

$(ActionBinder.bind);

or

window.addEventListener("DOMContentLoaded", ActionBinder.bind);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment