Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

9.2. Speeding Up Global Event Triggering

Problem

Global event triggering implicates calling all the event handlers bound for a certain event, on all available elements.

It is performed by calling jQuery.trigger() without passing any DOM element as context. It is nearly the same as calling trigger() on all the elements that have one or more bindings to the corresponding event, something like this:

jQuery('#a1,#a2,div.b5').trigger('someEvent');

Triggering globally is obviously simpler because you don’t need to know all the elements that need to be triggered.

It’s quite useful for certain situations but can also be a slow process at times. Although it’s been optimized since jQuery 1.3, it still requires going through all the elements registered to jQuery’s event system. This can cause short (or not so short) hangs every time an event is triggered like this.

Solution

One possible solution is to have one or more global objects that will act as event listeners. These elements can be DOM elements or not. All global events will be bound and triggered on one of these elements.

Instead of doing something like this:

jQuery('#text1').bind('change-page', function(e, title){
    jQuery(this).text( 'Page is ' + title );
});
jQuery('#text2').bind('change-page', function(e, title){
    jQuery(this).text( 'At ' + title + ' Page' );
});
jQuery.trigger('change-page', 'Inbox');

you’d do something like this:

jQuery.page = jQuery({}); // Just an empty object
jQuery.page.bind('change', function(e, title){ jQuery('#text1').text( ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required