简体   繁体   中英

How to bubble custom jQuery event to window.document?

I have written an absolutely positioned drop-down menu. I am triggering a custom event when this menu opens:

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

This works great when I know which instance of ps.DropDown to target:

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

However, I would like for my custom event to bubble up to 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 any way to accomplish this with jQuery?

EDIT to add a example by analogy

A click on a button element will trigger an event. This event will continue to bubble up the parent-element chain until it reaches window.document (unless propagation is stopped by an event listener). I am interested in synthesizing this behavior for custom events such that if event.stopPropagation() is not called, it will bubble to window.document (or $.event, or some other window global, it doesn't matter)

I think you're looking for calling $.event.trigger manually:

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

The last parameter is used for the "onlyHandlers" flag, false in this case as we want to trigger the elements handlers and then trigger again on each parentNode. In this fashion you can bind "myCustomEvent" to anything in between the window and the node where this event originated.

if I need custom events globally without a specific reference, I trigger the events on the body of the page

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

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

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

Never used the window.document as an event target.

It's not neccessary to trigger 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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM