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