0
# EventEmitter
1
2
Event-based JavaScript for the browser providing a comprehensive event management system with RegExp support, listener manipulation, and Node.js-compatible API. Zero dependencies with full TypeScript support.
3
4
## Package Information
5
6
- **Package Name**: wolfy87-eventemitter
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES5) with TypeScript definitions
9
- **Installation**: `npm install wolfy87-eventemitter`
10
- **License**: Unlicense (public domain)
11
12
## Core Imports
13
14
ES6/TypeScript:
15
16
```typescript
17
import EventEmitter from "wolfy87-eventemitter";
18
```
19
20
Or with namespace import:
21
22
```typescript
23
import * as EventEmitter from "wolfy87-eventemitter";
24
```
25
26
CommonJS/Node.js:
27
28
```javascript
29
const EventEmitter = require("wolfy87-eventemitter");
30
```
31
32
AMD:
33
34
```javascript
35
define(["EventEmitter"], function(EventEmitter) {
36
// Use EventEmitter
37
});
38
```
39
40
Browser global:
41
42
```html
43
<script src="EventEmitter.js"></script>
44
<script>
45
// EventEmitter is available globally
46
</script>
47
```
48
49
## Basic Usage
50
51
```typescript
52
import EventEmitter from "wolfy87-eventemitter";
53
54
// Create an EventEmitter instance
55
const emitter = new EventEmitter();
56
57
// Add a listener
58
emitter.on("data", (value) => {
59
console.log("Received:", value);
60
});
61
62
// Emit an event
63
emitter.emit("data", "Hello World");
64
65
// Add a listener that runs only once
66
emitter.once("error", (err) => {
67
console.error("Error occurred:", err);
68
});
69
70
// Remove a specific listener
71
function myHandler(data) {
72
console.log("Handler:", data);
73
}
74
emitter.on("test", myHandler);
75
emitter.off("test", myHandler);
76
77
// Remove all listeners for an event
78
emitter.removeAllListeners("data");
79
```
80
81
## Architecture
82
83
EventEmitter is built around several key components:
84
85
- **Universal Module Pattern**: Compatible with browser globals, CommonJS, AMD, and ES6 modules
86
- **RegExp Event Matching**: Support for regular expressions in event names for pattern-based listeners
87
- **Method Chaining**: All methods return the EventEmitter instance for fluent API usage
88
- **Duplicate Prevention**: Automatically prevents duplicate listener registration
89
- **Auto-removal System**: Listeners can be automatically removed based on return values
90
- **Namespace Protection**: No-conflict mode for global usage scenarios
91
92
## Capabilities
93
94
### Event Listener Management
95
96
Core functionality for retrieving and inspecting registered event listeners.
97
98
```typescript { .api }
99
/**
100
* Returns the listener array for the specified event.
101
* Supports RegExp patterns for matching multiple events.
102
*/
103
getListeners(event: string | RegExp): Function[] | { [event: string]: Function[] };
104
105
/**
106
* Always returns listeners in object format, useful for internal operations.
107
*/
108
getListenersAsObject(event: string | RegExp): { [event: string]: Function[] };
109
110
/**
111
* Converts array of listener objects to array of listener functions.
112
*/
113
flattenListeners(listeners: { listener: Function }[]): Function[];
114
```
115
116
### Adding Event Listeners
117
118
Methods for registering event listeners with various behaviors.
119
120
```typescript { .api }
121
/**
122
* Adds a listener function to the specified event.
123
* Prevents duplicate registration and supports RegExp events.
124
*/
125
addListener(event: string | RegExp, listener: Function): EventEmitter;
126
127
/**
128
* Alias of addListener for Node.js compatibility.
129
*/
130
on(event: string | RegExp, listener: Function): EventEmitter;
131
132
/**
133
* Adds a listener that automatically removes itself after first execution.
134
*/
135
addOnceListener(event: string | RegExp, listener: Function): EventEmitter;
136
137
/**
138
* Alias of addOnceListener for Node.js compatibility.
139
*/
140
once(event: string | RegExp, listener: Function): EventEmitter;
141
142
/**
143
* Bulk add listeners to events. Supports object mapping for multiple events.
144
*/
145
addListeners(event: string | RegExp, listeners: Function[]): EventEmitter;
146
addListeners(event: MultipleEvents): EventEmitter;
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
const emitter = new EventEmitter();
153
154
// Basic listener registration
155
emitter.on("message", (text) => console.log(text));
156
157
// RegExp event matching (requires defineEvent first)
158
emitter.defineEvent("user:login");
159
emitter.defineEvent("user:logout");
160
emitter.on(/user:.*/, (action) => console.log("User action:", action));
161
162
// One-time listeners
163
emitter.once("init", () => console.log("Application initialized"));
164
165
// Bulk listener registration
166
emitter.addListeners("error", [
167
(err) => console.error("Error 1:", err),
168
(err) => console.error("Error 2:", err),
169
]);
170
171
// Multiple events with object mapping
172
emitter.addListeners({
173
"start": () => console.log("Started"),
174
"stop": () => console.log("Stopped"),
175
});
176
```
177
178
### Removing Event Listeners
179
180
Methods for unregistering event listeners in various ways.
181
182
```typescript { .api }
183
/**
184
* Removes a specific listener function from an event.
185
* Supports RegExp patterns for bulk removal.
186
*/
187
removeListener(event: string | RegExp, listener: Function): EventEmitter;
188
189
/**
190
* Alias of removeListener for Node.js compatibility.
191
*/
192
off(event: string | RegExp, listener: Function): EventEmitter;
193
194
/**
195
* Bulk remove listeners from events. Supports object mapping.
196
*/
197
removeListeners(event: string | RegExp, listeners: Function[]): EventEmitter;
198
removeListeners(event: MultipleEvents): EventEmitter;
199
200
/**
201
* Removes all listeners from specified event, or all events if no parameter.
202
*/
203
removeEvent(event?: string | RegExp): EventEmitter;
204
205
/**
206
* Alias of removeEvent, mirrors Node.js API.
207
*/
208
removeAllListeners(event?: string | RegExp): EventEmitter;
209
```
210
211
### Event Definition
212
213
Methods for pre-defining events, required for RegExp listener matching.
214
215
```typescript { .api }
216
/**
217
* Pre-defines an event name for RegExp pattern matching.
218
* Required before using RegExp patterns with listeners.
219
*/
220
defineEvent(event: string): EventEmitter;
221
222
/**
223
* Pre-defines multiple event names using defineEvent.
224
*/
225
defineEvents(events: string[]): EventEmitter;
226
```
227
228
**Usage Examples:**
229
230
```typescript
231
const emitter = new EventEmitter();
232
233
// Define events for RegExp matching
234
emitter.defineEvents(["user:login", "user:logout", "user:register"]);
235
236
// Now RegExp patterns will work
237
emitter.on(/user:.*/, (data) => console.log("User event:", data));
238
emitter.emit("user:login", { userId: 123 });
239
```
240
241
### Event Emission
242
243
Methods for triggering events and executing their listeners.
244
245
```typescript { .api }
246
/**
247
* Emits an event with optional arguments array.
248
* Supports RegExp patterns for emitting to multiple events.
249
*/
250
emitEvent(event: string | RegExp, args?: any[]): EventEmitter;
251
252
/**
253
* Alias of emitEvent.
254
*/
255
trigger(event: string | RegExp, args?: any[]): EventEmitter;
256
257
/**
258
* Emits an event with variadic arguments (Node.js style).
259
* Arguments are passed individually to listeners.
260
*/
261
emit(event: string | RegExp, ...args: any[]): EventEmitter;
262
```
263
264
**Usage Examples:**
265
266
```typescript
267
const emitter = new EventEmitter();
268
269
// Basic event emission
270
emitter.on("greet", (name, greeting) => {
271
console.log(`${greeting}, ${name}!`);
272
});
273
274
// Using emit (variadic arguments)
275
emitter.emit("greet", "Alice", "Hello");
276
277
// Using emitEvent (arguments array)
278
emitter.emitEvent("greet", ["Bob", "Hi"]);
279
280
// RegExp emission (to multiple events)
281
emitter.defineEvents(["log:info", "log:warn", "log:error"]);
282
emitter.on(/log:.*/, (level, message) => {
283
console.log(`[${level}] ${message}`);
284
});
285
emitter.emit(/log:.*/, "info", "Application started");
286
```
287
288
### Advanced Configuration
289
290
Low-level methods for bulk manipulation and auto-removal configuration.
291
292
```typescript { .api }
293
/**
294
* Low-level bulk listener manipulation (add/remove).
295
* Used internally by addListeners and removeListeners.
296
*/
297
manipulateListeners(
298
remove: boolean,
299
event: string | RegExp | MultipleEvents,
300
listeners?: Function[]
301
): EventEmitter;
302
303
/**
304
* Sets the return value that triggers automatic listener removal.
305
* Default value is true.
306
*/
307
setOnceReturnValue(value: any): EventEmitter;
308
```
309
310
### Static Methods
311
312
Class-level utility methods.
313
314
```typescript { .api }
315
/**
316
* Reverts global EventEmitter to previous value and returns this version.
317
* Useful for avoiding naming conflicts in browser environments.
318
*/
319
static noConflict(): typeof EventEmitter;
320
```
321
322
**Usage Example:**
323
324
```typescript
325
// In browser global context
326
const MyEventEmitter = EventEmitter.noConflict();
327
// Now EventEmitter global is restored to previous value
328
// Use MyEventEmitter for this library's functionality
329
```
330
331
## Types
332
333
```typescript { .api }
334
/**
335
* Hash object for manipulating multiple events simultaneously.
336
*/
337
interface MultipleEvents {
338
[event: string]: Function | Function[];
339
}
340
341
/**
342
* Main EventEmitter class for managing events.
343
* Can be extended to provide event functionality in other classes.
344
*/
345
class EventEmitter {
346
constructor();
347
}
348
349
/**
350
* Namespace containing all EventEmitter types and interfaces.
351
*/
352
declare namespace Wolfy87EventEmitter {
353
interface MultipleEvents {
354
[event: string]: any; // Function | Function[]
355
}
356
357
export class EventEmitter {
358
// All instance and static methods as defined above
359
}
360
}
361
```
362
363
## Error Handling
364
365
The EventEmitter will throw `TypeError` exceptions in the following cases:
366
367
- **Invalid Listener**: When `addListener`, `addOnceListener`, `on`, or `once` methods receive a non-function argument as the listener parameter
368
- **Type Validation**: Uses internal `isValidListener()` helper for type checking
369
370
**Error Handling Example:**
371
372
```typescript
373
const emitter = new EventEmitter();
374
375
try {
376
emitter.on("test", "not a function"); // Throws TypeError
377
} catch (error) {
378
console.error("Invalid listener:", error.message);
379
}
380
```
381
382
## Advanced Usage Patterns
383
384
### Extending EventEmitter
385
386
```typescript
387
class MyClass extends EventEmitter {
388
constructor() {
389
super();
390
}
391
392
doSomething() {
393
// Perform action
394
this.emit("action", "something happened");
395
}
396
}
397
```
398
399
### Auto-removal Configuration
400
401
```typescript
402
const emitter = new EventEmitter();
403
404
// Configure custom auto-removal value
405
emitter.setOnceReturnValue("REMOVE_ME");
406
407
emitter.on("test", () => {
408
console.log("This listener will be removed");
409
return "REMOVE_ME"; // Triggers auto-removal
410
});
411
412
emitter.emit("test"); // Listener executes and removes itself
413
emitter.emit("test"); // No output - listener was removed
414
```
415
416
### Complex RegExp Patterns
417
418
```typescript
419
const emitter = new EventEmitter();
420
421
// Define various event namespaces
422
emitter.defineEvents([
423
"api:get:users",
424
"api:post:users",
425
"api:get:posts",
426
"db:connect",
427
"db:query"
428
]);
429
430
// Listen to all API events
431
emitter.on(/^api:.*/, (method, resource, data) => {
432
console.log(`API ${method} ${resource}:`, data);
433
});
434
435
// Listen to specific patterns
436
emitter.on(/^api:get:.*/, (resource, query) => {
437
console.log(`GET ${resource} with query:`, query);
438
});
439
```