@irrelon/emitter 6.1.0 → 6.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,8 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = tab
5
+ end_of_line = lf
6
+ charset = utf-8
7
+ trim_trailing_whitespace = true
8
+ insert_final_newline = false
@@ -15,12 +15,12 @@ export interface EmitterAnyEventsInterface {
15
15
  export type EmitterEventsInterface<T> = {
16
16
  [K in keyof T]: T[K];
17
17
  };
18
- interface WithStar {
18
+ export interface WithStar {
19
19
  "*"?: (eventName: string, ...args: any[]) => void;
20
20
  }
21
21
  export type EmitterEventsWithStar<T> = EmitterEventsInterface<T> & WithStar;
22
22
  /**
23
- * Creates a new class with the capability to emit events.
23
+ * Creates a new class with the ability to emit events.
24
24
  */
25
25
  export declare class Emitter<EventsInterface extends EmitterEventsWithStar<EventsInterface> = EmitterAnyEventsInterface> {
26
26
  _eventsEmitting: boolean;
@@ -33,6 +33,10 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
33
33
  };
34
34
  _eventsAllowDefer: boolean;
35
35
  _eventsDeferTimeouts: Record<any, number>;
36
+ _dispatchWindowEventsEnabled: boolean;
37
+ _dispatchPrefix?: string;
38
+ constructor(dispatchPrefix?: string, shouldDispatchWindowEvents?: boolean);
39
+ dispatchWindowEventsEnabled(shouldDispatchWindowEvents: boolean): void;
36
40
  /**
37
41
  * Attach an event listener to the passed event only if the passed
38
42
  * id matches the id for the event being fired.
@@ -117,6 +121,14 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
117
121
  off<EventName extends keyof EventsInterface>(eventName: EventName): this;
118
122
  _emitToSingleListener<EventName extends keyof EventsInterface>(listener: EventListenerCallback<EventsInterface[EventName]>, data: Parameters<EventsInterface[EventName]>): ReturnType<EventsInterface[EventName]> | ListenerReturnFlag;
119
123
  _emitToArrayOfListeners<EventName extends keyof EventsInterface>(arr: EventListenerCallback<EventsInterface[EventName]>[], data: Parameters<EventsInterface[EventName]>): (ReturnType<EventsInterface[EventName]> | ListenerReturnFlag)[];
124
+ /**
125
+ * Dispatches an event originating in our emitter to the browser's
126
+ * window object.
127
+ * @param eventName The name of the event to emit. This gets prefixed with the
128
+ * dispatch prefix if one is set.
129
+ * @param data
130
+ */
131
+ _emitToWindowDispatch<EventName extends keyof EventsInterface>(eventName: EventName, data: any): void;
120
132
  /**
121
133
  * Call an event listener by name. The `rpc()` function differs from `emit()` in
122
134
  * that it will only call and return data from the first event listener for the
@@ -150,7 +162,7 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
150
162
  * console.log("Result:", result);
151
163
  *
152
164
  * // The console output is:
153
- * // Arguments: data1 data2
165
+ * // Arguments: data1 data2
154
166
  * // Result: "foo"
155
167
  */
156
168
  rpc<EventName extends keyof EventsInterface>(eventName: EventName, ...data: Parameters<EventsInterface[EventName]>): ReturnType<EventsInterface[EventName]> | ListenerReturnFlag;
@@ -161,7 +173,7 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
161
173
  * @param {...any} data The arguments to send to any listening methods.
162
174
  * If you are sending multiple arguments, separate them with a comma so
163
175
  * that they are received by the function as separate arguments.
164
- * @return {number}
176
+ * @return {any[]} An array of all return values from all the listeners for the event.
165
177
  * @example #Emit an Event
166
178
  * // Emit the event named "hello"
167
179
  * myEntity.emit('hello');
@@ -174,7 +186,7 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
174
186
  * @example #Listen for Event Data
175
187
  * // Set a listener to listen for the data (multiple values emitted
176
188
  * // from an event are passed as function arguments)
177
- * myEntity.on('hello', function (arg1, arg2) {
189
+ * myEntity.on('hello', function (arg1, arg2) {
178
190
  * console.log("Arguments:", arg1, arg2);
179
191
  * return "foo";
180
192
  * }
@@ -186,15 +198,26 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
186
198
  * console.log("Result:", result);
187
199
  *
188
200
  * // The console output is:
189
- * // Arguments: data1 data2
201
+ * // Arguments: data1 data2
190
202
  * // Result: ["foo"]
191
203
  */
192
204
  emit<EventName extends keyof EventsInterface>(eventName: EventName, ...data: Parameters<EventsInterface[EventName]>): (ReturnType<EventsInterface[EventName]> | ListenerReturnFlag)[];
205
+ /**
206
+ * Emits an event by name and id.
207
+ * @param eventName The name of the event to emit.
208
+ * @param id The id of the event to emit.
209
+ * @param {...any} data The arguments to send to any listening methods.
210
+ * If you are sending multiple arguments, separate them with a comma so
211
+ * that they are received by the function as separate arguments.
212
+ * @return {any[]} An array of all return values from all the listeners for the event.
213
+ */
193
214
  emitId<EventName extends keyof EventsInterface>(eventName: EventName, id: string, ...data: Parameters<EventsInterface[EventName]>): (ReturnType<EventsInterface[EventName]> | ListenerReturnFlag)[];
194
215
  /**
195
- * Creates a persistent emitter record that will fire a listener if
196
- * one is added for this event after the emitStatic() call has been
197
- * made.
216
+ * Creates a persistent event. Once emitStatic() has been called, a
217
+ * persistent event is registered. Any existing event listeners will
218
+ * be called just like when you call emit(), however, any new
219
+ * listeners that are registered for this event via on() will also be
220
+ * called as soon as they are added.
198
221
  * @param eventName The name of the event to emit.
199
222
  * @param {...any} data Optional arguments to emit with the event.
200
223
  * @returns The emitter instance.
@@ -262,7 +285,6 @@ export declare class Emitter<EventsInterface extends EmitterEventsWithStar<Event
262
285
  */
263
286
  _processRemovalQueue(): void;
264
287
  }
265
- export declare function makeEmitter(obj: AnyConstructor, prototypeMode: boolean): Emitter;
266
- export declare function makeEmitter(obj: boolean): Emitter;
267
- export declare function makeEmitter(obj: Record<string, unknown>, prototypeMode: boolean): Emitter;
268
- export {};
288
+ export declare function makeEmitter<EventsInterface extends EmitterEventsWithStar<EventsInterface> = EmitterAnyEventsInterface>(obj: boolean): Emitter<EventsInterface>;
289
+ export declare function makeEmitter<EventsInterface extends EmitterEventsWithStar<EventsInterface> = EmitterAnyEventsInterface>(obj: Record<string, unknown>, prototypeMode: boolean): Emitter<EventsInterface>;
290
+ export declare function makeEmitter<EventsInterface extends EmitterEventsWithStar<EventsInterface> = EmitterAnyEventsInterface>(obj: AnyConstructor): Emitter<EventsInterface>;
@@ -8,16 +8,22 @@ var ListenerReturnFlag;
8
8
  ListenerReturnFlag["cancel"] = "!+_CANCEL";
9
9
  })(ListenerReturnFlag || (exports.ListenerReturnFlag = ListenerReturnFlag = {}));
10
10
  /**
11
- * Creates a new class with the capability to emit events.
11
+ * Creates a new class with the ability to emit events.
12
12
  */
13
13
  class Emitter {
14
- constructor() {
14
+ constructor(dispatchPrefix, shouldDispatchWindowEvents = false) {
15
15
  this._eventsEmitting = false;
16
16
  this._eventRemovalQueue = [];
17
17
  this._eventListeners = {};
18
18
  this._eventStaticEmitters = {};
19
19
  this._eventsAllowDefer = false;
20
20
  this._eventsDeferTimeouts = {};
21
+ this._dispatchWindowEventsEnabled = false;
22
+ this._dispatchPrefix = dispatchPrefix;
23
+ this._dispatchWindowEventsEnabled = shouldDispatchWindowEvents;
24
+ }
25
+ dispatchWindowEventsEnabled(shouldDispatchWindowEvents) {
26
+ this._dispatchWindowEventsEnabled = shouldDispatchWindowEvents;
21
27
  }
22
28
  /**
23
29
  * Attach an event listener to the passed event only if the passed
@@ -38,9 +44,7 @@ class Emitter {
38
44
  nonNullableEventListeners[id] = nonNullableEventListeners[id] || [];
39
45
  nonNullableEventListeners[id].push(listener);
40
46
  // Check for any static emitters, and fire the event if any exist
41
- if (!this._eventStaticEmitters ||
42
- !this._eventStaticEmitters[eventName] ||
43
- !this._eventStaticEmitters[eventName].length)
47
+ if (!this._eventStaticEmitters || !this._eventStaticEmitters[eventName] || !this._eventStaticEmitters[eventName].length)
44
48
  return this;
45
49
  // Emit events for each emitter
46
50
  for (let i = 0; i < this._eventStaticEmitters[eventName].length; i++) {
@@ -188,6 +192,22 @@ class Emitter {
188
192
  }
189
193
  return resultArr;
190
194
  }
195
+ /**
196
+ * Dispatches an event originating in our emitter to the browser's
197
+ * window object.
198
+ * @param eventName The name of the event to emit. This gets prefixed with the
199
+ * dispatch prefix if one is set.
200
+ * @param data
201
+ */
202
+ _emitToWindowDispatch(eventName, data) {
203
+ if (typeof window === "undefined")
204
+ return;
205
+ if (!this._dispatchWindowEventsEnabled) {
206
+ return;
207
+ }
208
+ const finalEventName = (this._dispatchPrefix ? `${this._dispatchPrefix}.${eventName}` : eventName);
209
+ window.dispatchEvent(new CustomEvent(finalEventName, { detail: data }));
210
+ }
191
211
  /**
192
212
  * Call an event listener by name. The `rpc()` function differs from `emit()` in
193
213
  * that it will only call and return data from the first event listener for the
@@ -221,7 +241,7 @@ class Emitter {
221
241
  * console.log("Result:", result);
222
242
  *
223
243
  * // The console output is:
224
- * // Arguments: data1 data2
244
+ * // Arguments: data1 data2
225
245
  * // Result: "foo"
226
246
  */
227
247
  rpc(eventName, ...data) {
@@ -259,7 +279,7 @@ class Emitter {
259
279
  * @param {...any} data The arguments to send to any listening methods.
260
280
  * If you are sending multiple arguments, separate them with a comma so
261
281
  * that they are received by the function as separate arguments.
262
- * @return {number}
282
+ * @return {any[]} An array of all return values from all the listeners for the event.
263
283
  * @example #Emit an Event
264
284
  * // Emit the event named "hello"
265
285
  * myEntity.emit('hello');
@@ -272,7 +292,7 @@ class Emitter {
272
292
  * @example #Listen for Event Data
273
293
  * // Set a listener to listen for the data (multiple values emitted
274
294
  * // from an event are passed as function arguments)
275
- * myEntity.on('hello', function (arg1, arg2) {
295
+ * myEntity.on('hello', function (arg1, arg2) {
276
296
  * console.log("Arguments:", arg1, arg2);
277
297
  * return "foo";
278
298
  * }
@@ -284,12 +304,22 @@ class Emitter {
284
304
  * console.log("Result:", result);
285
305
  *
286
306
  * // The console output is:
287
- * // Arguments: data1 data2
307
+ * // Arguments: data1 data2
288
308
  * // Result: ["foo"]
289
309
  */
290
310
  emit(eventName, ...data) {
311
+ this._emitToWindowDispatch(eventName, data);
291
312
  return this.emitId(eventName, "*", ...data);
292
313
  }
314
+ /**
315
+ * Emits an event by name and id.
316
+ * @param eventName The name of the event to emit.
317
+ * @param id The id of the event to emit.
318
+ * @param {...any} data The arguments to send to any listening methods.
319
+ * If you are sending multiple arguments, separate them with a comma so
320
+ * that they are received by the function as separate arguments.
321
+ * @return {any[]} An array of all return values from all the listeners for the event.
322
+ */
293
323
  emitId(eventName, id, ...data) {
294
324
  if (!this._eventListeners || (!this._eventListeners[eventName] && !this._eventListeners["*"])) {
295
325
  return [];
@@ -317,9 +347,11 @@ class Emitter {
317
347
  return emitterResult;
318
348
  }
319
349
  /**
320
- * Creates a persistent emitter record that will fire a listener if
321
- * one is added for this event after the emitStatic() call has been
322
- * made.
350
+ * Creates a persistent event. Once emitStatic() has been called, a
351
+ * persistent event is registered. Any existing event listeners will
352
+ * be called just like when you call emit(), however, any new
353
+ * listeners that are registered for this event via on() will also be
354
+ * called as soon as they are added.
323
355
  * @param eventName The name of the event to emit.
324
356
  * @param {...any} data Optional arguments to emit with the event.
325
357
  * @returns The emitter instance.
@@ -40,7 +40,8 @@ describe("Emitter", () => {
40
40
  it("Creates emitter instance by instantiation", () => {
41
41
  var _a, _b;
42
42
  const myClass = new Emitter_1.Emitter();
43
- myClass.on("moo", () => { });
43
+ myClass.on("moo", () => {
44
+ });
44
45
  assert_1.default.strictEqual((_a = myClass._eventListeners) === null || _a === void 0 ? void 0 : _a.moo["*"].length, 1, "Listener registered on event");
45
46
  myClass.off("moo");
46
47
  assert_1.default.strictEqual(!((_b = myClass._eventListeners) === null || _b === void 0 ? void 0 : _b.moo) ||
@@ -241,11 +242,15 @@ describe("Emitter", () => {
241
242
  it("Cancels all listeners (event)", () => {
242
243
  var _a, _b, _c, _d, _e, _f, _g;
243
244
  const myClass = new Emitter_1.Emitter();
244
- const listener1 = () => { };
245
- const listener2 = () => { };
246
- myClass.on("moo", () => { });
245
+ const listener1 = () => {
246
+ };
247
+ const listener2 = () => {
248
+ };
249
+ myClass.on("moo", () => {
250
+ });
247
251
  assert_1.default.strictEqual((_a = myClass._eventListeners) === null || _a === void 0 ? void 0 : _a.moo["*"].length, 1, "Listeners registered on event");
248
- myClass.on("moo", "testId", () => { });
252
+ myClass.on("moo", "testId", () => {
253
+ });
249
254
  assert_1.default.strictEqual((_b = myClass._eventListeners) === null || _b === void 0 ? void 0 : _b.moo["testId"].length, 1, "Listeners registered on event");
250
255
  myClass.on("moo", listener1);
251
256
  assert_1.default.strictEqual((_c = myClass._eventListeners) === null || _c === void 0 ? void 0 : _c.moo["*"].length, 2, "Listeners registered on event");
@@ -259,11 +264,15 @@ describe("Emitter", () => {
259
264
  it("Cancels id-based listeners (event, id)", () => {
260
265
  var _a, _b, _c, _d, _e, _f, _g;
261
266
  const myClass = new Emitter_1.Emitter();
262
- const listener1 = () => { };
263
- const listener2 = () => { };
264
- myClass.on("moo", () => { });
267
+ const listener1 = () => {
268
+ };
269
+ const listener2 = () => {
270
+ };
271
+ myClass.on("moo", () => {
272
+ });
265
273
  assert_1.default.strictEqual((_a = myClass._eventListeners) === null || _a === void 0 ? void 0 : _a.moo["*"].length, 1, "Listeners registered on event");
266
- myClass.on("moo", "testId", () => { });
274
+ myClass.on("moo", "testId", () => {
275
+ });
267
276
  assert_1.default.strictEqual((_b = myClass._eventListeners) === null || _b === void 0 ? void 0 : _b.moo["testId"].length, 1, "Listeners registered on event");
268
277
  myClass.on("moo", listener1);
269
278
  assert_1.default.strictEqual((_c = myClass._eventListeners) === null || _c === void 0 ? void 0 : _c.moo["*"].length, 2, "Listeners registered on event");
@@ -276,11 +285,15 @@ describe("Emitter", () => {
276
285
  it("Cancels listener-based listeners (event, listener)", () => {
277
286
  var _a, _b, _c, _d, _e, _f;
278
287
  const myClass = new Emitter_1.Emitter();
279
- const listener1 = () => { };
280
- const listener2 = () => { };
281
- myClass.on("moo", () => { });
288
+ const listener1 = () => {
289
+ };
290
+ const listener2 = () => {
291
+ };
292
+ myClass.on("moo", () => {
293
+ });
282
294
  assert_1.default.strictEqual((_a = myClass._eventListeners) === null || _a === void 0 ? void 0 : _a.moo["*"].length, 1, "Listeners registered on event");
283
- myClass.on("moo", "testId", () => { });
295
+ myClass.on("moo", "testId", () => {
296
+ });
284
297
  assert_1.default.strictEqual((_b = myClass._eventListeners) === null || _b === void 0 ? void 0 : _b.moo["testId"].length, 1, "Listeners registered on event");
285
298
  myClass.on("moo", listener1);
286
299
  assert_1.default.strictEqual((_c = myClass._eventListeners) === null || _c === void 0 ? void 0 : _c.moo["*"].length, 2, "Listeners registered on event");
@@ -293,11 +306,15 @@ describe("Emitter", () => {
293
306
  it("Cancels id-based + listener-based listeners (event, id, listener)", () => {
294
307
  var _a, _b, _c, _d, _e, _f;
295
308
  const myClass = new Emitter_1.Emitter();
296
- const listener1 = () => { };
297
- const listener2 = () => { };
298
- myClass.on("moo", () => { });
309
+ const listener1 = () => {
310
+ };
311
+ const listener2 = () => {
312
+ };
313
+ myClass.on("moo", () => {
314
+ });
299
315
  assert_1.default.strictEqual((_a = myClass._eventListeners) === null || _a === void 0 ? void 0 : _a.moo["*"].length, 1, "Listeners registered on event");
300
- myClass.on("moo", "testId", () => { });
316
+ myClass.on("moo", "testId", () => {
317
+ });
301
318
  assert_1.default.strictEqual((_b = myClass._eventListeners) === null || _b === void 0 ? void 0 : _b.moo["testId"].length, 1, "Listeners registered on event");
302
319
  myClass.on("moo", listener1);
303
320
  assert_1.default.strictEqual((_c = myClass._eventListeners) === null || _c === void 0 ? void 0 : _c.moo["*"].length, 2, "Listeners registered on event");