Skip to content

Instantly share code, notes, and snippets.

@leandrowd
Last active August 29, 2015 14:25
Show Gist options
  • Save leandrowd/54ebc848f03912062d1e to your computer and use it in GitHub Desktop.
Save leandrowd/54ebc848f03912062d1e to your computer and use it in GitHub Desktop.
Hijacking $.on to add namespace to every event
var oldFnOn = $.fn.on;
$.fn.on = function( types, selector, data, fn ) {
var currentType = types;
// 'click' will became 'click.plugin'
// 'click.deep' will became 'click.plugin.deep'
function addNamespace(type) {
var namespacedType = type.split('.');
namespacedType.splice(1, 0, 'plugin');
return namespacedType.join('.');
};
// Types can be a map of types/handlers
if ( typeof types !== "object" ) {
types = addNamespace(types);
console.debug('hijacking on:', currentType, '->', types);
}
return oldFnOn.call( this, types, selector, data, fn );
};
// look at the console to see the logs
$(document).on('click', '.demo', function(e){
console.log('click - namespace:', e.handleObj.namespace);
});
console.debug('triggering click');
$('.demo').trigger('click');
$(document).on('click.deep', '.demo', function(e){
console.log('click - namespace:', e.handleObj.namespace);
});
console.debug('triggering click');
$('.demo').trigger('click');
$(document).on({
'click': function(e){
console.log('click - namespace:', e.handleObj.namespace, '(from the object)');
},
'click.deppObj': function(e){
console.log('click - namespace:', e.handleObj.namespace, '(from the object)');
}
}, '.demo');
console.debug('triggering click');
$('.demo').trigger('click');
// unbind only the click.plugin.deep
console.debug('unbinding .deep');
$(document).off('.deep');
console.debug('triggering click');
$('.demo').trigger('click');
// unbind everything
console.debug('unbinding .plugin');
$(document).off('.plugin');
console.debug('triggering click');
$('.demo').trigger('click');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment