Skip to content

Instantly share code, notes, and snippets.

@adam-lynch
Created May 12, 2013 22:11
Show Gist options
  • Save adam-lynch/5565101 to your computer and use it in GitHub Desktop.
Save adam-lynch/5565101 to your computer and use it in GitHub Desktop.
Overriding of jQuery's .on() for specific event delegation; so that it can be called with ':only' at the end of the selector and the event will only be attached to that exact element (well, selector) only, i.e. excluding its descendants (well, technically it will be but the descendants will ignore the event and also prevent it from bubbling up i…
(function($){
var _oldOn = $.fn.on;
$.fn.on = function( types, selector, data, fn, one ){
var selectorSegments = selector.match(/^(.+?)(:only)?$/);
if ( selectorSegments[2] ) {
_oldOn.call(this, types, selectorSegments[1] + ' *', data, function(e){
e.stopPropagation();
}, one);
arguments[1] = selectorSegments[1];
}
return _oldOn.apply(this, arguments);
};
})(jQuery);
// Proof:
$('body').on('click', 'p:only', function(){alert('works with .on()!');})
.one('click', 'p:only', function(){alert("works with .one()! Click again to see this won't be shown again");})
.delegate('p:only', 'click', function(){alert("works with .delegate()!");})
//Oh, and this *won't* do anything now :D
.find('p *').trigger('click');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment