Last active
August 29, 2015 13:57
-
-
Save kobachi/9755518 to your computer and use it in GitHub Desktop.
Automated Action Binding for JavaScript
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
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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
$(ActionBinder.bind);
or
window.addEventListener("DOMContentLoaded", ActionBinder.bind);