Skip to content

Instantly share code, notes, and snippets.

@qborreda
Forked from pbojinov/data-action.js
Last active May 30, 2021 11:18
Show Gist options
  • Save qborreda/ece17b03009442277064 to your computer and use it in GitHub Desktop.
Save qborreda/ece17b03009442277064 to your computer and use it in GitHub Desktop.
JavaScript event hooking with data-action
// 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