jQuery: bubbleBind jQuery Plugin to bind bubbling events
January 18th, 2010 by jeremychoneUPDATE 2010-02-26: JQuery 1.4.2 added the delegate method, which does exactly that. Use the jQuery.delegate rather than bubbleBind (I just kepp the code below for reference)
bubbleBind is a jQuery plugin to conveniently bind bubbling events for given child targets. It is very similar to jQuery.bind and uses it under the cover (as well as jQuery.is()). Nothing magic, just simple, convenient, and familiar.
Example
<div id="parentDiv"> <span>one</span> <span>two</span> </div>
$("#parentDiv").bubbleBind("span","click",function(){
alert("you clicked on an span tag: " + $(this).html());
});
Plugin code
License free: use as you want, modify as you can, attribute as you feel.
(function($) {
/**
* Allow to bind a bubbled-event at the parent level for a given child (matching the childSelector).
* The selected element(s) will be considered the parent(s), and the childSelector will filter the target element.
* If, an only if, the target match the childSelector, then, the handler will be called. The key work "this" will
* point to the target document element (as in jQuery bind)
*
* Example:
* $("#parentDiv").bubbleBind("span","click",function(){
* alert("you clicked on an span tag: " + $(this).html());
* });
*
* @param {String} childSelector the jQuery selector for the targeted child. This will be use in $target.is(childSelector)
* @param {String} a jQuery evenType (same a jQuery bind)
* @param {Function} the handler function
*
* TODO: need to support eventData
*/
$.fn.bubbleBind = function(childSelector,eventType,handler) {
// iterate and reformat each matched element
return this.each(function() {
var $parentElement = $(this);
//bind the even to the parent
$parentElement.bind(eventType,function(event){
//get the target and test the target against the childSelector
var $target = $(event.target);
if ($target.is(childSelector)){
// If matched, call the handler method using the target html element as reference
// Note: Might be a smarter and more conventional way to do this. Feel free to suggest.
$target.get(0).bubbleBindHandler = handler;
$target.get(0).bubbleBindHandler(event);
}
});
});
};
})(jQuery);