JQuery listen globally for custom event

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 would like indication.bind('custom-event') receive a trigger from the function OtherThing , without having two, to explicitly know about each other. Is it possible? My only solution so far is to bind the listener and the event to the body ... it seems sloppy - is there a better way?

+6
source share
1 answer

In JavaScripts, the events triggered by each HTML element are propagated to their parents, therefore, to solve your problem and make any element capable of handling a custom event without doing something different from $('*').bind('custom-event') to associate the listener with a common parent for all elements, body or html elements:]

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

And then in the event handler you can access the element that raised the event by accessing the 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'); 
+18
source

Source: https://habr.com/ru/post/911229/


All Articles