Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'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?

like image 906
Will Avatar asked Mar 20 '12 17:03

Will


People also ask

What is the jQuery method for attaching a custom event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

Which jQuery function can be used to override events in jQuery?

Projects In JavaScript & JQuery Use the off() method to override jQuery event handlers. This method is used to remove an event handler. The on() method is used to attach one or more event handler.

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

Which jQuery method triggers or binds a function to the error event of selected elements?

jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.


1 Answers

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');
like image 166
Rafael Verger Avatar answered Nov 03 '22 02:11

Rafael Verger