Question

I am looking to create events in Javascript using the same methodology as JQuery- Does anyone know how JQuery does it?

My reasoning is that using raw Javascript such this:

var myEvent = new CustomEvent("userLogin", eventProperties);

...does not actually work on Android native browser, as it does not support DOM Level 3 like Chrome and other browsers do.

However, JQuery does work on Android's stock browser, and simply uses:

$.event.trigger('MyEvent');

My question is, what is the code behind this? I tried to find it by going through JQuery's source code, but cannot get my head around it!

Was it helpful?

Solution

The fundamental thing here is this: When you hook an event handler up with jQuery, jQuery doesn't directly add that handler to the DOM element. Instead, jQuery hooks up a handler of its own on the DOM element (if it doesn't already have one on it). When the event occurs, jQuery looks at the list of jQuery-registered handlers for the event and fires them in order. (There are several reasons for this; initially it was primarily around IE memory leaks and the fact that IE fired handlers in one order, and everyone else in a different order; so jQuery took over and ensured the order.)

(You might be able to see where I'm going with this...)

So when you use trigger, jQuery sends the synthetic event to the DOM element, but it doesn't rely on that synthetic event to work; it calls the handlers you've registered through jQuery directly. In fact, it sets a flag so that it knows that it's done that, so if the browser does send the event to jQuery's handler for it, jQuery knows to ignore it (since it's already done its work).

You can see this in all its glory starting with line 4,464 of the current uncompressed jQuery file.

So basically jQuery's build its own pub/sub system, and only uses the browser event system as an input to it. So custom events don't usually have to talk to the browser at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top