-
-
Save Wryhder/b6d3f37bd43ee1f1bcf61e2e1d7d90a5 to your computer and use it in GitHub Desktop.
JavaScript event hooking with data-action
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
// Set up HTML hooks without id or extra classes | |
<button data-action="openLogin">Login</button> | |
<a href="javascript:;" data-action="openEditor">Link</a> | |
// Using [data-action=""] selectors instead of class selectors when binding events in JavaScript | |
var actions = { | |
openLogin: openLoginWindow, | |
openEditor: function() { ... } | |
//.... | |
}; | |
// Delegate click events on the body to those DOM nodes which have a data-action attribute | |
$('body').on('click', '[data-action]', function() { | |
var action = $(this).data('action'); | |
if (action in actions) { | |
actions[action].apply(this, arguments); | |
} | |
}); | |
// If future components need to be hooked as well, we would just need to add them to the actions object | |
actions.newHook = function() {}; | |
actions.otherHook = componentFunction; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment