Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe a JS event, when you only know PART of the event name?

I've inherited some JS (that I can't change) that fires a bunch of events:

jQuery(document).trigger('section:' + section);
// where "section" changes dynamically

And I want to observe for ALL of these events, and parse out the value for section, and do something different depending on it's contents.

If it didn't change I could do this:

jQuery(document).on('section:top', doStuff );

But how do I observe an event if I only know the first part of that event name?

like image 793
Joshua Soileau Avatar asked Dec 15 '14 14:12

Joshua Soileau


1 Answers

You cannot listen for all events in the style of $().on('section:*'), unfortunately. If you can change the code, I would do the following:

jQuery(document).trigger({
    type: 'section',
    section: section
});

Then you listen for it and don't need to parse anything out

jQuery(document).on('section', function(e){
    if (e.section === 'top') {
        // Something happened to the top section
    }
 });

If you want to minimize your code changes, leave the old event in there, that way existing code will be unaffected.

A different approach would be to use event namespaces.

jQuery(document).trigger('section.' + section);

jQuery(document).on('section', function(e){
    if (e.namespace === 'top') {
        // Something happened to the top section
    }
});

I, however, prefer the first approach because event namespaces are most commonly used for a different purpose: to be able to remove events without being forced to keep a reference to the handler itself. See http://css-tricks.com/namespaced-events-jquery/ and http://ejohn.org/apps/workshop/adv-talk/#13. I prefer to use styles that other developers are used to, if they do the job.

like image 121
Juan Mendes Avatar answered Nov 14 '22 05:11

Juan Mendes