Mad Rapper X
Mad Rapper X

Reputation: 311

How does event handling work internally within JavaScript?

Specifically Spidermonkey.

I know you write functions and attach them to events to handle them.

Where is the onClick handler defined and how does the JS engine know to fire onClick events when the user clicks?

Any keywords, design patterns, links, etc are appreciated.

UPDATE

Aggregating links I find useful here:

http://www.w3.org/TR/DOM-Level-2-Events/events.html

https://github.com/joyent/node/blob/master/src/node_events.cc

http://mxr.mozilla.org/mozilla/source/dom/src/events/nsJSEventListener.cpp

Upvotes: 13

Views: 6560

Answers (2)

c-smile
c-smile

Reputation: 27450

  1. HTML uses sink/bubble event propagation schema: http://catcode.com/domcontent/events/capture.html
  2. There are "physical" events (mouse, keyboard) and logical/synthesized ones (focus,click, value_changed, etc.)
  3. onClick is a logical event - generated as a result of mouse, touch and/or keyboard events.
  4. Mouse (or finger touch) originated click event is a result of mouse down, move and up events. Note that mouse down, move and up are sinking/bubbling events. Target element(s) in these "primordial" events will be the target(or source) of the click event. If mouse-down/up events have different targets (DOM element) then their common parent is used.
  5. Sequence of mouse down, move and up events may produce different logical events: click, swipe/scroll, etc.

I believe this is a full list of basic concepts.

Upvotes: 4

Boris Zbarsky
Boris Zbarsky

Reputation: 35054

SpiderMonkey itself doesn't have anything involving event handling. Events are purely a DOM thing.

The click event is fired by the browser code (the thing embedding SpiderMonkey), not by SpiderMonkey itself. See http://hg.mozilla.org/mozilla-central/file/e60b8be7a97b/content/events/src/nsEventStateManager.cpp for the code that's responsible for dispatching things like click.

The browser is also what defines setter methods that take an assignment to the onclick property and turn it into an event listener registration. See http://hg.mozilla.org/mozilla-central/file/e60b8be7a97b/dom/base/nsDOMClassInfo.cpp#l7624 which is called from nsEventReceiverSH::SetProperty and handles properties whose name (id in this code) passes the IsEventName test.

When event listeners are registered and an event is fired, the event dispatcher manages calls to the listeners; the nsJSEventListener link you found is the glue that converts a C++ HandleEvent call into a call to a JS function.

So in your case, you want some sort of registration/unregistration mechanism for listeners and then your implementation will fire events and dispatch them to listeners. How you do this last part is pretty open-ended; the Gecko implementation has a lot of constraints due to needing to implement the DOM Events specification, but you should be able to do something much simpler.

Upvotes: 9

Related Questions