steveosoule
12/12/2014 - 6:39 PM

Effective Event Binding with jQuery

Effective Event Binding with jQuery

<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>
// FROM: http://www.sitepoint.com/effective-event-binding-jquery/

$.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(e) {
  console.log('menu toggled');
  $.hook('nav-menu').toggle();
}

function trackClick(e){
  // Do some analytics click tracking
  console.log(e.target + 'clicked');
}

// ---- Usability ---- //
  $.hook('nav-menu-toggle').on('click.usability', toggleNavMenu);

// ---- Analytics ---- //
  // 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');