Last active
August 29, 2015 14:25
-
-
Save leandrowd/54ebc848f03912062d1e to your computer and use it in GitHub Desktop.
Hijacking $.on to add namespace to every event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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