Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't listen to global event in jQuery

Another question on stackoverflow pointed out that it should be possible to trigger an event on all listning objects using:

$.event.trigger('customEvent');

However this does not seem to work for me in an example like:

$('body').bind('customEvent', function(){ alert('Working!'); });

Am I doing something completely wrong, or has this great functionality been disabled?

like image 631
Mr.H Avatar asked Apr 02 '13 11:04

Mr.H


1 Answers

It looks like that functionality has been removed. Browsing through the tags I managed to find this TODO in v1.8b1:

// TODO: Stop taunting the data cache; remove global events and always attach to document

And it was removed as of v1.9.0.

There is nothing stopping you from implementing it based on the old source code here (v1.6.2), but it looks like it was doing naughty things talking to jQuery.cache so it's probably best to live without it or come up with another solution.

$('*').trigger('customEvent');

Perhaps? (jsFiddle)

Or a more efficient approach of keeping track of each subscription and calling .trigger() on that.

jsFiddle

var customSubs;

$.fn.subscribeCustom = function (fn) {
    this.on('customEvent', fn);
    if (!customSubs)
        customSubs = this;
    else
        customSubs = customSubs.add(this);
};

$('span').subscribeCustom(function () {
    alert('span!');
});
$('div').subscribeCustom(function () {
    alert('div!');
});

customSubs.trigger('customEvent');
like image 174
Daniel Imms Avatar answered Oct 04 '22 11:10

Daniel Imms