Fancy Emitter
A new take on JavaScript's EventEmitter class. Makes use of types and the newest JS features.
This event emitter makes use of ES6 newset built in features, asynchronous functions and generators.
Comparison against Node.js 'events' module
fancy-emitter |
Node.js events |
|
---|---|---|
Strongly Typed | ☑ | ☒ |
Asynchronous | ☑ | ☒ |
Iterable | ☑ | ☒ |
Cancellable Events | ☑ | ☒ |
Magic Events | ☒ | ☑ |
Memory Leaks | ☒ | ☑ |
How to Use
Create a new emitter.
Set a listener on the action.
Or listen to many events which will occur.
for await of action total += value
Then activate the emitter whenever you please action.activate(12)
Emitters and their listeners can also be cancelled. To do this create an "unsafe" emitter instead.
The loop listeners may be gracefully broken out of
cancellableAction.cancel
or, with an error state by deactivating with the error
cancellableAction.deactivateError'err'
Emitters can be merged with the helper.
// { name: "action" } | // { name: "actionNumber", value: number } >
Emitters can be cloned with the helper.
cloned.onceconsole.log`Hello `original.activate'world'
Emitters can be filtered with the helper.
action.activate'hi'action.activate'hey'action.activate'hello' // promise is now resolved.
Emitters can be have listeners bound and later removed using the following helpers.
action.activate1action.activate2cancelaction.activate3 // not console.log'd
Classic
This can also be used like a classic event emitter with callbacks set to the on
and once
methods.
action.onconsole.logdata action.activate'hello'action.activate'world'
These listeners provide more functionality in that they can be cancelled.
action.once action.activate'hello'action.activate'world' action.activate'this will be shown'setTimeoutaction.activate"this won't. Since it occurs AFTER the cancel has time to propagate"
Take a look at the tests for more examples.
API
The emitter is the union between a few interfaces.
- A Listener (or SafeListener), which only detects when an event occurred.
- A Broadcaster which can only trigger events.
- Or an "unsafe" Brodcaster which can also trigger errors.
In the above interfaces the OneArgFn
type refers to a function which takes an argument iff it isn't void
.
It uses an optional argument if a union with void and another value is present.
Roadmap
Possibly, a handler for just deactivations
This would be a shorthand for the fn
function here.
try catcherr
CDN
Use the CDN from unpkg!
Or as an ES module