jQuery listen globally for custom event
Asked Answered
G

1

10

A simplified version of what i'm trying to do is as follows:

var indication = $('#some-div');
indication.bind('custom-event', function() { ... }


 // ... later on!

 function OtherThing() {
   $(this).trigger('custom-event');
 }

I'd like indication.bind('custom-event') to receive the trigger from function OtherThing without the two having to explicitly know about each other. Is this possible? My only solution so far is to bind both the listener and the event to body ... this seems sloppy -- is there a better way?

Gran answered 20/3, 2012 at 17:48 Comment(2)
What do you mean by "without the two having to explicitly know about each other"?Abirritate
@RobW - not sure how to explain it further, other then reading the code ... I know I can change $(this).trigger into $('#some-div).trigger and have it work but that defeats the purpose. As I stated my current solution is to bind both the listener and the emitters to $('body')Gran
M
24

In JavaScripts, the events triggered on each HTML Element are propagated to their parents, so, to solve your problem and make any element be capable to handle the custom event without do something wrong like $('*').bind('custom-event') is to bind the listener to a common parent for all elements, the body or html elements :]

So, you only need to bind the event to body or html element. Then, when any element, inside the choosen parent element, trigger the custom event, it will be propagated to this parent element.

And then, in the event handler, you can access the element that has triggered the event by accessing target attribute for the event object: event.target

So, the code should be:

$('body').bind('custom-event', function(e){
  var $element = e.target;
});

$('#anyElement').trigger('custom-event');
Mandamandaean answered 20/3, 2012 at 17:54 Comment(2)
You'd better bind the event to document instead of 'body'. Also, this will not work if the element is not part of the document (e.g. not injected / iframe).Abirritate
It's right, @RobW. If the element isn't part of the same document of the parent element, the event will not be propagated to it.Mandamandaean

© 2022 - 2024 — McMap. All rights reserved.