Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
Mad Rapper X Avatar asked Apr 22 '11 17:04

Mad Rapper X


People also ask

How do event handlers work in JavaScript?

Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.

How does event loop work in JavaScript?

The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.


1 Answers

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.

like image 130
Boris Zbarsky Avatar answered Nov 15 '22 14:11

Boris Zbarsky