How to bubble a jQuery custom event in window.document?

I wrote an absolutely drop-down menu. I fire a custom event when this menu opens:

ps.DropDown.prototype._onOpenComplete = function() { $(this).trigger('MENU_OPEN', [this]); } 

This works fine when I know which instance of ps.DropDown is targeted:

 var dd = new ps.DropDown(); $(dd).on('MENU_OPEN', fn); 

However, I would like my custom event to appear in window.document if the event is not stopped from propagating. For example:

 var dd = new ps.DropDown(); $(dd).on('MENU_OPEN', function(event, instance) { // this would stop bubbling to $(window.document) // event.stopPropagation(); }); $(window.document).on('MENU_OPEN', function(event, instance) { // bubbled! }); 

Is there a way to accomplish this using jQuery?

EDIT add an example by analogy

Clicking on a button element will trigger an event. This event will continue to bubble up the chain of parent elements until it reaches window.document (unless propagation is stopped by the event listener). I am interested in synthesizing this behavior for custom events, so if event.stopPropagation () is not called, it will bubble in window.document (or $ .event or some other global window, it does not matter)

+7
source share
3 answers

I think you are looking to manually call $ .event.trigger:

 $.event.trigger('myCustomEvent', someDataObj, someDomElement, false); 

The last parameter is used for the "onlyHandlers" flag, in this case false, because we want to run element handlers and then run again on each parentNode. This way you can bind "myCustomEvent" to anything between the window and the node where this event occurred.

+10
source

If I need custom events globally without a specific link, I fire events in the body of the page

 $('body').trigger('MENU_OPEN', [this]); 

Now you can listen to this event anywhere without knowing anything about your DropDown

 $('body').on('MENU_OPEN',function(event, dropDown){ // bubbled }); 

window.document never been used as an event target.

-one
source

No need to fire custom events from a DOM element:

 $(window.document).bind('dropDownHasOpened', function() { console.log($(this)); // 'this' is window.document }); ps.DropDown.prototype._onOpenComplete = function() { $.event.trigger('dropDownHasOpened'); } 
-one
source

All Articles