Capture All The Events (javascript)
Solution 1:
Some event basics:
- Events are dispatched "on" a DOM object (usually an element) that is the event target.
- Events can firstly propagate down to child elements in a capture phase. This phase is rarely used since it wasn't supported by some widely used browsers until recently.
- Events can secondly propagate up to parent elements in a bubbling phase. This phase is commonly used.
- Some events don't propagate, they have neither a capture or bubble phase (e.g. focus, blur and submit events). Some events that propagate in some browsers don't propagate in others.
- DOM elements that respond to events have an event handler. It can be set to listen for particular events and call a listener function when that event reaches the element, either during capture, bubbling or if the element is an event target.
- Listeners can cancel propagation, e.g. a click event on a span inside a link can cancel propagation so the link doesn't get the click
Given the above, it is a practical impossibility to "capture all events" using the Events API. It would require establishing a listener for every event type on every element and be impossible to capture custom events because you have to know about them to set an appropriate listener.
I imagine there would need to be a prototyping of dispatchEvent or something
dispatchEvent is a method of an Event instance, it's not specified to be a constructor (there is no requirement for it to have an internal [[Construct]]
method) so not practical to use as such. Browsers aren't required to implement prototype inheritance for host objects (though most do), and the implementation details of host objects and methods are largely hidden, so this is not an option.
You might try extending the Event API, but you really should not mess with host objects.
It seems that you are concerned about dynamically added elements. There is a strategy called "event delegation", where you work out the events you need to listen for, then setup listeners as close to the event targets as you can on an element that doesn't change (e.g. a table element if you are dynamically adding and removing table rows, or a container div for other elements) for the specific event types you need to respond to.
You can also have the functions that are modifying the DOM dispatch custom events to add listeners or whatever.
Post a Comment for "Capture All The Events (javascript)"