Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 621
thesmart Avatar asked Feb 14 '12 02:02

thesmart


People also ask

What is event bubbling in jQuery?

Event bubbling directs an event to its intended target, and works like this: When an object (like a button) is clicked, an event is directed to the object. If an event handler is set for the object, the event handler is triggered. Then the event bubbles up (like a bubble in water) to the objects parent.

What does event stopPropagation () do?

Event.stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.

How do you trigger a click event?

The HTMLElement.click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


1 Answers

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.

like image 167
Alexis Abril Avatar answered Oct 03 '22 16:10

Alexis Abril