W3C JavaScript events for custom objects
npm install eventtargeterAdd familiar, standard JavaScript event handling methods for custom objects based on
EventTarget.
Based on original code from mrdoob and
ShareIt-project.
Supports stricter API requirements and a number of additional methods to mimicEventTarget.
``html`
`js`
const {
EventTargetFactory, ShimEventTarget,
ShimEvent, ShimCustomEvent,
ShimDOMException, setPrototypeOfCustomEvent
} = EventTargeter;
or just:
`js`
import {
EventTargetFactory, ShimEventTarget,
ShimEvent, ShimCustomEvent,
ShimDOMException, setPrototypeOfCustomEvent
} from './node_modules/eventtargeter/EventTarget-es6.js';
`shell`
npm install
`js`
const EventTarget = require('eventtarget');
`html
// Adding events to custom object
const Car = function () {
this.start = function () {
this.dispatchEvent({type: 'start', message: 'vroom vroom!'});
};
};
Object.assign(Car.prototype, EventTarget.prototype);
// Using events
const car = new Car();
car.addEventListener('start', function (ev) {
alert(ev.message);
});
car.start();
`
If you inherit from EventTarget, you can invoke the (non-standard)__setOptions
constructor with options. See .
The following behave as with the standard EventTarget methodscapture
(as possible). Options supported include the standard options, once
(including expressed as a boolean), as well as (which auto-removespassive
the listener after execution) and (which prevents the listenerpreventDefault
from using even if the event passed to the target wascancelable).
- addEventListener(type, listener, options) - These standard methods cannotaddDefaultEventListener
prevent execution of the non-standard
/addLateEventListener-added methods.
- removeEventListener(type, listener, options)
- dispatchEvent(ev) - Will check as appropriate the event's type,bubbles
or cancelable (which can all be set with invocation of theEvent
constructor, ) or the readonly eventPhase and defaultPrevented.target
The properties , currentTarget, eventPhase, anddefaultPrevented
will be set as appropriate.
- on* = function (ev) {}; (e.g., onclick) - Can use return false to
prevent the default (but this will not stop propagation or stop immediate
propagation as per regular JavaScript behavior (unlike jQuery which stops
propagation)).
Note that if an error throws within one of the listeners, an ErrorEvent willwindow
be dispatched to as expected, or, if on Node, you can listen insteaduncaughtException
for . Alternatively, you may implement your own__userErrorEventHandler method (see below).
The following are non-standard methods:
- __setOptions(optsObject) - Set custom options. Currently limited todefaultSync
which can be set to true to execute the default behaviorsdispatchEvent
even before late listeners and before returns. DefaultsetTimeout(..., 0)
listeners will otherwise be triggered after .
- hasEventListener(type, listener, options) - Detects whether a given event
listener exists
- - Allows maintenance of functions
which execute prior to all other event listeners. These should generally
not stop propagation or prevent the default behavior since that should
normally be left up to the consumer. Note that capturing and bubbling do
not occur for early listeners.
- - Allows maintenance of functionspreventDefault
which execute subsequent to all normal event listeners and which can be
prevented via (or checked via defaultPrevented) unlessstopPropagation
the event dispatched to the target is not cancelable. These events will
not be stopped by or stopImmediatePropagation alone.defaultPrevented
(You can check the property in these methods toe.preventDefault()
determine whether the user has called and thus tostopPropagation
decide whether to continue on with some default behavior.) These cannot
use to stop execution of late event listeners (thoughstopImmediatePropagation
they can use to prevent further execution of
other default listeners). Note that capturing and bubbling do not occur
for default listeners.
- - Allows maintenance of functionsdefaultSync
which execute subsequent to all event listeners (unless default behaviors
are set to run asynchronously) and which cannot be stopped. Should be
used within implementations only to avoid unexpected behavior by
consumers. If default event listeners fire after late listeners (when
is true), late listeners can prevent default event execution.stopPropagation
Note that capturing and bubbling do not occur for late listeners.
has no relevance (even if occurring before defaultstopImmediatePropagation
listeners) (though may be used to prevent
further execution of other late listeners).
- __getParent - This method can be implemented by consumers to supportEventTarget
hierarchical events (those with bubbling and/or capturing). Should
itself return an object.
- __userErrorEventHandler(errorObj, triggerGlobalErrorEventCb) - ThisErrorEvent
method can be implemented by consumers to override the default behavior
relating to triggering of a global upon encountering exceptionsErrorEvent
within handlers. Will be passed an object representing the thrown error
and a callback which can be invoked to trigger the usual global dispatchEvent
behavior. An example usage is for an IndexedDB transaction object which must
abort a transaction upon encountering an error in a user event handler. This
method could be used to implement the aborting or it could merely rethrow
the error object passed to it and allow the internal consuming code to
catch it and abort the transaction. If using this handler, you should ideally
use a flag in your calling code and utilize that in this handler in order to
distinguish between your own specific internal error events and those dispatched
by users in their own calls (which shouldn't ever throwEventTarget
as that would be non-standard for the real ).
Because Object.setPrototypeOf is not supported in all environments (e.g.,ShimCustomEvent
React-Native currently) and it comes at a cost for performance without
much strong of a benefit (besides introspecting on the prototype chain),
these calls to associate with ShimEvent no longer occursetPrototypeOfCustomEvent
automatically. If desired (e.g., for passing IDL tests), they can be set
using .
ShimEvent, ShimCustomEvent, and ShimDOMException should generally
follow the standard API for the objects they are shimming.
- See todo's' within code.
- Align with new
standard.
- Option to set global event (Does this redefine or alter the object for capturing, bubbling, etc.?)
- Support worker.onerror
- Allow __getParent to return a promise to allow async bubbling
- Consider refactoring so that all methods (as with properties) are private and
all early/late/default listeners, parent retrieval, and option setting are
done dynamically at class creation time or, alternatively, at any time via
ES6 Symbols (Babel) which are somewhat more "safely" namespaced. Remove
hasEventListener as it is necessarily run-time and non-standard.
- Add getEventHandler and setEventHandler methods (ala Mozilla)?
- Provide option for early, late, and default listeners to capture and
bubble (will need to propagate independently of normal listeners)?
- Add another type of late listener or config which executes even
after async default?
- Demo click() (for capturing/bubbling/propagation) andsubmit()` (for default and default prevention) on implementations on JSON.