0

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!

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Oli C
  • 1,120
  • 13
  • 36

1 Answers1

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Doesn't jQuery also add an extra attribute to elements with listeners so it has its own unique identifier for the element? – RobG Aug 01 '14 at 14:49
  • @RobG: Yes, it does: The jQuery event handlers associated with the element are stored in the same data cache that the `data` function manages, and the first time jQuery initializes the data cache for an element, it adds the jQuery expando property to the element object (`jQuery111008836618564091623` or similar). That property's value is the key it uses to look up information (including event handlers) in the data cache. – T.J. Crowder Aug 01 '14 at 15:01
  • 1
    Thanks for the explanation Crowder- I didn't realise JQuery went about it in this way. I think I'll just include JQuery and save myself re-writing functionality to do this, as not worth the time investment in this instance. Thanks again. – Oli C Aug 01 '14 at 16:52