jerkovicl
12/15/2014 - 10:30 AM

Event Binding with jQuery

Event Binding with jQuery

//nav menu toggle
//list of space-separated hook names on an element
<button data-hook="nav-menu-toggle video-pause click-track">Toggle Nav Menu</button>
<nav data-hook="nav-menu">
    <ul>
        <li><a href="/">West Philadelphia</a></li>
        <li><a href="/cab">Cab Whistling</a></li>
        <li><a href="/throne">Throne Sitting</a></li>
    </ul>
</nav>
$('[data-hook="nav-menu-toggle"]').on('click', function() {
    $('[data-hook="nav-menu"]').toggle();
});

  • or
$.extend({
    hook: function(hookName) {
        var selector;
        if(!hookName || hookName === '*') {
            // select all data-hooks
            selector = '[data-hook]';
        } else {
            // select specific data-hook
            selector = '[data-hook~="' + hookName + '"]';
        }
        return $(selector);
    }
});

function toggleNavMenu() {
    $.hook('nav-menu').toggle();
}
 
$.hook('nav-menu-toggle').on('click', toggleNavMenu);

//finding any hook name
$.hook('click-track'); // returns the button as expected

//selecting all hook elemenents on page
// both are equivalent
$.hook();
$.hook('*');

Working with Multiple Events

list of events to be handled by a single event handler:

$.hook('nav-menu-toggle').on('click keydown mouseenter', trackAction);

handling multiple events with different event handlers, using object notation:

$.hook('nav-menu-toggle').on({
    'click': trackClick,
    'keydown': trackKeyDown,
    'mouseenter': trackMouseEnter
});

unbinding multiple events at same time:

// unbinds keydown and mouseenter
$.hook('nav-menu-toggle').off('keydown mouseenter');
$.hook('click-track').off('click', trackClick);
 
// nuclear option: unbinds everything
$.hook('nav-menu-toggle').off();

using namespaces:

// binds a click event in the "analytics" namespace
$.hook('click-track').on('click.analytics', trackClick);
 
// unbinds only click events in the "analytics" namespace
$.hook('click-track').off('click.analytics');

multiple namespaces:

// binds a click event in both the "analytics" and "usability" namespaces
$.hook('click-track').on('click.analytics.usability', trackClick);
 
// unbinds any events in either the "analytics" OR "usability" namespaces
$.hook('click-track').off('.usability .analytics');
 
// unbinds any events in both the "analytics" AND "usability" namespaces
$.hook('click-track').off('.usability.analytics');

// free all elements on the page of any "analytics" event handling
$('*').off('.analytics');