UNPKG

1.88 kBMarkdownView Raw
1# component-emitter
2
3> Simple event emitter
4
5## Install
6
7```sh
8npm install component-emitter
9```
10
11## Usage
12
13As an `Emitter` instance:
14
15```js
16import Emitter from 'component-emitter';
17
18const emitter = new Emitter();
19
20emitter.emit('🦄');
21```
22
23As a mixin:
24
25```js
26import Emitter from 'component-emitter';
27
28const user = {name: 'tobi'};
29Emitter(user);
30
31user.emit('I am a user');
32```
33
34As a prototype mixin:
35
36```js
37import Emitter from 'component-emitter';
38
39Emitter(User.prototype);
40```
41
42## API
43
44### new Emitter()
45
46Create a new emitter.
47
48### Emitter(object)
49
50Use it as a mixin. For example a plain object may become an emitter, or you may extend an existing prototype.
51
52### Emitter#on(event, listener)
53
54Register an event handler that listens to a specified event.
55
56### Emitter#once(event, listener)
57
58Register a one-time event handler for a specified event.
59
60### Emitter#off(event, listener)
61
62Remove a specific event handler for a specified event.
63
64### Emitter#off(event)
65
66Remove all event handlers for a specified event.
67
68### Emitter#off()
69
70Remove all event handlers for all events.
71
72### Emitter#emit(event, ...arguments)
73
74Emit an event, invoking all handlers registered for it.
75
76### Emitter#listeners(event)
77
78Retrieve the event handlers registered for a specific event.
79
80### Emitter#listenerCount(event)
81
82Get the count of listeners for a specific event.
83
84### Emitter#listenerCount()
85
86Get the count of all event handlers in total.
87
88### Emitter#hasListeners(event)
89
90Check if there are any handlers registered for a specific event.
91
92### Emitter#hasListeners()
93
94Check if there are any handlers registered for any event.
95
96## FAQ
97
98### How does it differ from the Node.js EventEmitter?
99
100It's simpler and more lightweight, and it works in any JavaScript environment, not just Node.js. It also provides mixin functionality to add event handling to existing objects without needing inheritance.