/
events.ts
672 lines (602 loc) · 17.6 KB
/
events.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Backbone.js 1.2.3
// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// https://backbonejs.org
//
// The Events object is a typesafe conversion of Backbones Events object:
// https://github.com/jashkenas/backbone/blob/05fde9e201f7e2137796663081105cd6dad12a98/backbone.js#L119-L374
// Priority: Higher number makes the listener be called earlier.
const uniqueId = (function () {
const prefixes: Record<string, number | undefined> = Object.create(null);
return function (prefix: string) {
const unique = prefixes[prefix] || 1;
prefixes[prefix] = unique + 1;
return `${prefix}${unique}`;
};
})();
function once<T extends (..._: any) => any>(cb: T): T {
let hasRun = false;
let result: ReturnType<T>;
return function (this: any, ...args: any) {
if (hasRun === false) {
hasRun = true;
result = cb.apply(this, args);
}
return result;
} as T;
}
export interface EventCallback extends Function {
_callback?: Function;
}
interface EventListener {
obj: any;
objId: string;
id: string;
listeningTo: EventListeners;
count: number;
}
interface EventListeners {
[id: string]: EventListener;
}
interface EventHandler {
callback: EventCallback;
context: any;
ctx: any;
listening: EventListener;
priority: number;
}
interface EventHandlers {
[name: string]: EventHandler[];
}
export interface EventMap {
[name: string]: EventCallback;
}
interface EventIteratee<T, U> {
(events: U, name: string, callback: Function | undefined, options: T): U;
}
interface EventTriggerer {
(events: EventHandler[], args: any[]): void;
}
interface OnApiOptions {
context: any;
ctx: any;
listening: any;
priority: number;
}
interface OffApiOptions {
context: any;
listeners: any;
}
// Regular expression used to split event strings.
const eventSplitter = /\s+/;
/**
* Iterates over the standard `event, callback` (as well as the fancy multiple
* space-separated events `"change blur", callback` and jQuery-style event
* maps `{event: callback}`).
*/
function eventsApi<T extends {}, U>(
iteratee: EventIteratee<T, U>,
events: U,
name: EventMap | string | undefined,
callback: EventCallback | undefined,
options: T,
): U {
let i = 0,
names: string[];
const anyOptions = options as any;
if (name && typeof name === "object") {
// Handle event maps.
if (
callback !== void 0 &&
"context" in options &&
anyOptions["context"] === void 0
) {
anyOptions["context"] = callback;
}
for (names = Object.keys(name); i < names.length; i++) {
events = eventsApi(
iteratee,
events,
names[i],
name[names[i]],
options,
);
}
} else if (name && typeof name === "string" && eventSplitter.test(name)) {
// Handle space separated event names by delegating them individually.
for (names = name.split(eventSplitter); i < names.length; i++) {
events = iteratee(events, names[i], callback, options);
}
} else {
// Finally, standard events.
events = iteratee(events, <any>name, callback, options);
}
return events;
}
/**
* The reducing API that adds a callback to the `events` object.
*/
function onApi(
events: EventHandlers,
name: string,
callback: EventCallback | undefined,
options: OnApiOptions,
): EventHandlers {
if (callback) {
const handlers = (events[name] ||= []);
const context = options.context,
ctx = options.ctx,
listening = options.listening,
priority = options.priority;
if (listening) {
listening.count++;
}
handlers.push({
callback: callback,
context: context,
ctx: context || ctx,
listening: listening,
priority: priority,
});
handlers.sort((a, b) => b.priority - a.priority);
}
return events;
}
/**
* The reducing API that removes a callback from the `events` object.
*/
function offApi(
events: EventHandlers | undefined,
name: string,
callback: EventCallback | undefined,
options: OffApiOptions,
): EventHandlers | undefined {
if (!events) {
return;
}
let i = 0,
listening: EventListener;
const context = options.context,
listeners = options.listeners;
// Delete all events listeners and "drop" events.
if (!name && !callback && !context) {
const ids = Object.keys(listeners || {});
for (; i < ids.length; i++) {
listening = listeners[ids[i]];
delete listeners[listening.id];
delete listening.listeningTo[listening.objId];
}
return;
}
const names = name ? [name] : Object.keys(events || {});
for (; i < names.length; i++) {
name = names[i];
const handlers = events[name];
// Bail out if there are no events stored.
if (!handlers) {
break;
}
// Replace events if there are any remaining. Otherwise, clean up.
const remaining: EventHandler[] = [];
for (let j = 0; j < handlers.length; j++) {
const handler = handlers[j];
if (
(callback &&
callback !== handler.callback &&
callback !== handler.callback._callback) ||
(context && context !== handler.context)
) {
remaining.push(handler);
} else {
listening = handler.listening;
if (listening && --listening.count === 0) {
delete listeners[listening.id];
delete listening.listeningTo[listening.objId];
}
}
}
// Update tail event if the list has any events. Otherwise, clean up.
if (remaining.length) {
events[name] = remaining;
} else {
delete events[name];
}
}
if (Object.keys(events || {}).length !== 0) {
return events;
}
}
/**
* Reduces the event callbacks into a map of `{event: onceWrapper`.}
* `offer` unbinds the `onceWrapper` after it has been called.
*/
function onceMap(
map: EventMap,
name: string,
callback: EventCallback | undefined,
offer: Function,
): EventMap {
if (callback) {
const listener: EventCallback = (map[name] = once(function (
this: any,
...args: any
) {
offer(name, listener);
callback.apply(this, args);
}));
listener._callback = callback;
}
return map;
}
/**
* Handles triggering the appropriate event callbacks.
*/
function triggerApi(
objEvents: EventHandlers,
name: string,
_callback: Function | undefined,
args: any[],
triggerer: EventTriggerer = triggerEvents,
): EventHandlers {
if (objEvents) {
const events = objEvents[name];
let allEvents = objEvents["all"];
if (events && allEvents) {
allEvents = allEvents.slice();
}
if (events) {
triggerer(events, args);
}
if (allEvents) {
triggerer(allEvents, [name].concat(args));
}
}
return objEvents;
}
/**
* A difficult-to-believe, but optimized internal dispatch function for
* triggering events. Tries to keep the usual cases speedy (most internal
* Backbone events have 3 arguments).
*/
function triggerEvents(events: EventHandler[], args: any[]) {
let ev: EventHandler,
i = -1;
const l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l) {
(ev = events[i]).callback.call(ev.ctx);
}
return;
case 1:
while (++i < l) {
(ev = events[i]).callback.call(ev.ctx, a1);
}
return;
case 2:
while (++i < l) {
(ev = events[i]).callback.call(ev.ctx, a1, a2);
}
return;
case 3:
while (++i < l) {
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
}
return;
default:
while (++i < l) {
(ev = events[i]).callback.apply(ev.ctx, args);
}
return;
}
}
/**
* An event object.
*/
export class Event {
/**
* The name of the event.
*/
private _name: string;
/**
* Has {@link Event.stopPropagation} been called?
*/
private _isPropagationStopped = false;
/**
* Has {@link Event.preventDefault} been called?
*/
private _isDefaultPrevented = false;
/**
* Create a new Event instance.
*/
constructor(name: string) {
this._name = name;
}
/**
* Stop the propagation of this event. Remaining event handlers will not be executed.
*/
stopPropagation() {
this._isPropagationStopped = true;
}
/**
* Prevent the default action associated with this event from being executed.
*/
preventDefault() {
this._isDefaultPrevented = true;
}
/**
* Return the event name.
*/
get name(): string {
return this._name;
}
/**
* Has {@link Event.stopPropagation} been called?
*/
get isPropagationStopped(): boolean {
return this._isPropagationStopped;
}
/**
* Has {@link Event.preventDefault} been called?
*/
get isDefaultPrevented(): boolean {
return this._isDefaultPrevented;
}
}
/**
* A class that provides a custom event channel.
*
* You may bind a callback to an event with `on` or remove with `off`;
* `trigger`-ing an event fires all callbacks in succession.
*/
export class EventDispatcher {
/**
* Map of all handlers registered with the "on" function.
*/
private _events?: EventHandlers;
/**
* Map of all objects this instance is listening to.
*/
private _listeningTo?: EventListeners;
/**
* Map of all objects that are listening to this instance.
*/
private _listeners?: EventListeners;
/**
* A unique id that identifies this instance.
*/
private get _listenId(): string {
return this._savedListenId || (this._savedListenId = uniqueId("l"));
}
private _savedListenId?: string;
/**
* Bind an event to a `callback` function. Passing `"all"` will bind
* the callback to all events fired.
*/
on(eventMap: EventMap, context?: any): this;
on(
eventMap: EventMap,
callback?: EventCallback,
context?: any,
priority?: number,
): this;
on(
name: string,
callback: EventCallback,
context?: any,
priority?: number,
): this;
on(
nameOrMap: EventMap | string,
callback: EventCallback,
context?: any,
priority?: number,
) {
this.internalOn(nameOrMap, callback, context, priority);
return this;
}
/**
* Guard the `listening` argument from the public API.
*/
private internalOn(
name: EventMap | string,
callback: EventCallback | undefined,
context?: any,
priority = 0,
listening?: EventListener,
) {
this._events = eventsApi(
onApi,
this._events || <EventHandlers>{},
name,
callback,
{
context: context,
ctx: this,
listening: listening,
priority: priority,
},
);
if (listening) {
const listeners = this._listeners || (this._listeners = {});
listeners[listening.id] = listening;
}
}
/**
* Bind an event to only be triggered a single time. After the first time
* the callback is invoked, its listener will be removed. If multiple events
* are passed in using the space-separated syntax, the handler will fire
* once for each event, not once for a combination of all events.
*/
once(eventMap: EventMap, context?: any): this;
once(
name: string,
callback: EventCallback,
context?: any,
priority?: any,
): this;
once(
name: EventMap | string,
callback?: EventCallback,
context?: any,
priority?: number,
) {
// Map the event into a `{event: once}` object.
const events = eventsApi(
onceMap,
<EventMap>{},
name,
callback,
this.off.bind(this),
);
return this.on(events, void 0, context, priority);
}
/**
* Remove one or many callbacks. If `context` is null, removes all
* callbacks with that function. If `callback` is null, removes all
* callbacks for the event. If `name` is null, removes all bound
* callbacks for all events.
*/
off(): this;
off(eventMap: EventMap | undefined, context?: any): this;
off(
name: string | undefined,
callback?: EventCallback,
context?: any,
): this;
off(name?: EventMap | string, callback?: EventCallback, context?: any) {
if (!this._events) {
return this;
}
this._events = eventsApi(offApi, this._events, name, callback, {
context: context,
listeners: this._listeners,
});
return this;
}
/**
* Inversion-of-control versions of `on`. Tell *this* object to listen to
* an event in another object... keeping track of what it's listening to
* for easier unbinding later.
*/
listenTo(
obj: EventDispatcher,
name: EventMap | string,
callback?: EventCallback,
priority?: number,
) {
if (!obj) {
return this;
}
const id = obj._listenId;
const listeningTo = this._listeningTo || (this._listeningTo = {});
let listening = listeningTo[id];
// This object is not listening to any other events on `obj` yet.
// Setup the necessary references to track the listening callbacks.
if (!listening) {
const thisId = this._listenId;
listening = listeningTo[id] = {
obj: obj,
objId: id,
id: thisId,
listeningTo: listeningTo,
count: 0,
};
}
// Bind callbacks on obj, and keep track of them on listening.
obj.internalOn(name, callback, this, priority, listening);
return this;
}
/**
* Inversion-of-control versions of `once`.
*/
listenToOnce(obj: EventDispatcher, eventMap: EventMap): this;
listenToOnce(
obj: EventDispatcher,
name: string,
callback: EventCallback,
priority?: number,
): this;
listenToOnce(
obj: EventDispatcher,
name: EventMap | string,
callback?: EventCallback,
priority?: number,
) {
// Map the event into a `{event: once}` object.
const events = eventsApi(
onceMap,
<EventMap>{},
name,
callback,
this.stopListening.bind(this, obj),
);
return this.listenTo(obj, events, void 0, priority);
}
/**
* Tell this object to stop listening to either specific events ... or
* to every object it's currently listening to.
*/
stopListening(
obj?: EventDispatcher,
name?: EventMap | string,
callback?: EventCallback,
) {
const listeningTo = this._listeningTo;
if (!listeningTo) {
return this;
}
const ids = obj ? [obj._listenId] : Object.keys(listeningTo);
for (let i = 0; i < ids.length; i++) {
const listening = listeningTo[ids[i]];
// If listening doesn't exist, this object is not currently
// listening to obj. Break out early.
if (!listening) {
break;
}
listening.obj.off(name, callback, this);
}
if (Object.keys(listeningTo).length === 0) {
this._listeningTo = void 0;
}
return this;
}
/**
* Trigger one or many events, firing all bound callbacks. Callbacks are
* passed the same arguments as `trigger` is, apart from the event name
* (unless you're listening on `"all"`, which will cause your callback to
* receive the true name of the event as the first argument).
*/
trigger(name: Event | EventMap | string, ...args: any[]) {
if (!this._events) {
return this;
}
if (name instanceof Event) {
triggerApi(
this._events,
name.name,
void 0,
[name],
(events: EventHandler[], args: any[]) => {
let ev: EventHandler,
i = -1;
const l = events.length;
while (++i < l) {
if (name.isPropagationStopped) {
return;
}
ev = events[i];
ev.callback.apply(ev.ctx, args);
}
},
);
} else {
eventsApi(triggerApi, this._events, name, void 0, args);
}
return this;
}
}