Search code examples
javascripteventsinternalsspidermonkey

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


Solution

  • 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.