Event Emitter
Modern event emitter
Table of Contents
Features
- Simple 87 LOC
- Lightweight 522 bytes
- Performant
- Inheritable
Install
npm install --save @librpc/ee
or download dev or prod version
Usage
import EventEmitter from '@librpc/ee'
var emitter = new EventEmitter()
function listener (data) {
console.log(data)
}
emitter.on('event', listener)
emitter.emit('event', { foo: 'bar' }) // -> { foo: 'bar' } in console
emitter.off('event', listener)
API
Emitter
- new Emitter()
-
.on(event, listener) ⇒
Emitter
-
.off(event, listener) ⇒
Emitter
-
.emit(event, data) ⇒
Emitter
new Emitter()
Create an event emitter
Example
var emitter = new Emitter()
Emitter
emitter.on(event, listener) ⇒ Add listener to event. No context provided, use Function.prototype.bind(), arrow function or closure instead.
Kind: instance method of Emitter
Returns: Emitter
- Return self
Param | Type | Description |
---|---|---|
event | string |
Event name |
listener | listener |
Event listener |
Example
function listener (data) {
console.log(data)
}
emitter.on('event', listener)
Emitter
emitter.off(event, listener) ⇒ Remove listener from event.
Kind: instance method of Emitter
Returns: Emitter
- Return self
Param | Type | Description |
---|---|---|
event | string |
Event name |
listener | listener |
Event listener |
Example
emitter.off('event', listener)
Emitter
emitter.emit(event, data) ⇒ Trigger an event. Multiple arguments not supported, use destructuring instead.
Kind: instance method of Emitter
Returns: Emitter
- Return self
Param | Type | Description |
---|---|---|
event | string |
Event name |
data | * |
Event data |
Example
emitter.emit('event', { foo: 'bar' })
function
listener : Param | Type | Description |
---|---|---|
data | * |
Any data could be passed to event listener |
Benchmark
> @librpc/ee@1.0.5 bench D:\Projects\event-emitter
> node bench/
┌──────────────────────────────┬─────────┬───────────┬─────────┐
│ EMITTER │ ON │ EMIT │ OFF │
├──────────────────────────────┼─────────┼───────────┼─────────┤
│ events │ 99,258 │ 2,147,706 │ 187,842 │
├──────────────────────────────┼─────────┼───────────┼─────────┤
│ minivents │ 39,103 │ 1,737,633 │ 11,219 │
├──────────────────────────────┼─────────┼───────────┼─────────┤
│ mitt │ 134,112 │ 1,792,035 │ 231,187 │
├──────────────────────────────┼─────────┼───────────┼─────────┤
│ eventemitter3 │ 31,669 │ 2,188,591 │ 16,539 │
├──────────────────────────────┼─────────┼───────────┼─────────┤
│ ../dist/event-emitter.umd.js │ 142,386 │ 2,231,370 │ 269,298 │
└──────────────────────────────┴─────────┴───────────┴─────────┘
Development
Command | Description |
---|---|
npm run check |
Check standard code style by snazzy |
npm run build |
Wrap source code in UMD by rollup |
npm run bench |
Run benchmark |
npm run test |
Run tests by tape and compute code coverage by nyc |
npm run min |
Minify code by UglifyJS |
npm run docs |
Create docs by jsdoc-to-markdown |