Wilfred Hughes
Wilfred Hughes

Reputation: 31151

Triggering global events on jQuery 1.9

Given the following HTML:

<div id="foo">
    <p>hello world</p>
</div>

<p id="message">Event not yet triggered</p>

And the following JS:

$('#foo').bind('customEvent', function() {
    $('#message').text('Event triggered!');
});

$.event.trigger('customEvent');

My p tag is changed in jQuery 1.8 (JSFiddle), but not in 1.9 (JSFiddle).

Why is this? I can't see anything relevant in the changelog for 1.9. What's the best approach to use in 1.9+?

Upvotes: 0

Views: 127

Answers (1)

Pablojim
Pablojim

Reputation: 8582

If you want a global style event you can trigger events on the document body. Triggering events on more specific elements can be more efficient but this may not be what you want.

$(document.body).trigger('customEvent');

See: http://jsfiddle.net/7c8M7/

An alternative approach is to use a dedicated pub-sub library like: https://github.com/mroderick/PubSubJS

Upvotes: 1

Related Questions