forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 1
/
event_target.ts
56 lines (51 loc) · 1.85 KB
/
event_target.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
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import * as domTypes from "./dom_types";
import { requiredArguments } from "./util";
/* TODO: This is an incomplete implementation to provide functionality
* for Event. A proper spec is still required for a proper Web API.
*/
export class EventTarget implements domTypes.EventTarget {
public listeners: {
[type in string]: domTypes.EventListenerOrEventListenerObject[]
} = {};
public addEventListener(
type: string,
listener: domTypes.EventListenerOrEventListenerObject | null,
_options?: boolean | domTypes.AddEventListenerOptions
): void {
requiredArguments("EventTarget.addEventListener", arguments.length, 2);
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
if (listener !== null) {
this.listeners[type].push(listener);
}
}
public removeEventListener(
type: string,
callback: domTypes.EventListenerOrEventListenerObject | null,
_options?: domTypes.EventListenerOptions | boolean
): void {
requiredArguments("EventTarget.removeEventListener", arguments.length, 2);
if (type in this.listeners && callback !== null) {
this.listeners[type] = this.listeners[type].filter(
listener => listener !== callback
);
}
}
public dispatchEvent(event: domTypes.Event): boolean {
requiredArguments("EventTarget.dispatchEvent", arguments.length, 1);
if (!(event.type in this.listeners)) {
return true;
}
const stack = this.listeners[event.type].slice();
for (const stackElement of stack) {
if ((stackElement as domTypes.EventListenerObject).handleEvent) {
(stackElement as domTypes.EventListenerObject).handleEvent(event);
} else {
(stackElement as domTypes.EventListener).call(this, event);
}
}
return !event.defaultPrevented;
}
}