Search code examples
eventsjqueryevent-bubbling

jQuery prevent all event bubbling


I'm using jQuery with it's widget factory and using custom events to handle events in my application.

This means that all my event binding looks a lot like:

//...in the widget factory code

$(this.element).addClass('customEventClass');
$(this.element).bind('mysite.loadNextPage', $.proxy(this, 'loadNextPage');

and the events are triggered by doing:

$('.customEventClass').trigger('mysite.loadNextPage');

Because the events are directly bound to the elements that need to receive them, I don't need to have these custom events to bubble up through the DOM. I know I can check whether the even has bubbled up or not by doing this in the event handler code:

if (event.target != event.currentTarget) {
    event.stopPropagation();
    event.preventDefault();
    return;
}

But at the moment because most of the elements that are listening for the custom events don't have a handler registered for 'mysite.loadNextPage' there are 51 events generated where only 1 actually does anything. Is there a way to either:

  1. tell jQuery not to bubble these events at all or
  2. Add a default 'stop propagation' handler to all DOM objects that have class 'customEventClass' to stop them from bubbling up an event that they don't have a specific handler for.

Or are there any other good practices for only triggering events on elements that are interesting in those events, rather than having lots of events be triggered for elements that aren't interested in those events.


Solution

  • It looks like there's no good way to do it with jQuery as it is, but it's very easy to write a new function to allow this.

    First I wrote a new function to stop the event from bubbling(, and also log the event why not).

    function    eventWrapper(event){
    
        var logString = 'Event called: ' + event.type + ":" + event.namespace;
    
        if (jQuery.isFunction(this.log) == true) {
            this.log(logString);
        }
        else if (jQuery.isFunction(Logger.log) == true) {
            Logger.log(logString);
        }
        else{
            console.log(logString);
        }
    
        event.stopPropagation();
    }
    

    And now a new function that is added to jQuery.

    // A global GUID counter for objects
    guidWrapper: 1,
    
    proxyWrapper: function(wrappedFn, fn, context, wrapFn ) {
    
        var args, proxy, tmp;
    
        if ( typeof context === "string" ) {
            tmp = fn[ context ];
            context = fn;
            fn = tmp;
        }
    
        // Quick check to determine if target is callable, in the spec
        // this throws a TypeError, but we will just return undefined.
        if ( !jQuery.isFunction( fn ) ) {
            return undefined;
        }
    
        // Simulated bind
        args = core_slice.call( arguments, 3 );
        proxy = function() {
            wrappedFn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
            return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
        };
    
        // Set the guid of unique handler to the same of original handler, so it can be removed
        proxy.guid = fn.guid = fn.guid || jQuery.guid++;
    
        return proxy;
    },
    

    And then instead of binding the function like this:

    $(this.element).bind('click', $.proxy(this.click, this));
    

    Instead bind it like this.

    $(this.element).bind('click', $.proxyWrapper(eventWrapper, this.click, this));
    

    This means that when the event is triggered, the first element that is listening for that event will call event.stopPropagation on the event, and so it won't bubble up to other elements that may also be listening for that event.