2019-01-21 14:03:30 -05:00
|
|
|
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
|
2019-01-05 10:02:44 -05:00
|
|
|
import * as domTypes from "./dom_types";
|
2019-03-30 13:40:03 -04:00
|
|
|
import { requiredArguments } from "./util";
|
2019-01-05 10:02:44 -05:00
|
|
|
|
|
|
|
/* 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,
|
2019-03-09 12:30:38 -05:00
|
|
|
_options?: boolean | domTypes.AddEventListenerOptions
|
2019-01-05 10:02:44 -05:00
|
|
|
): void {
|
2019-03-30 13:40:03 -04:00
|
|
|
requiredArguments("EventTarget.addEventListener", arguments.length, 2);
|
2019-03-30 08:18:19 -04:00
|
|
|
if (!this.listeners.hasOwnProperty(type)) {
|
2019-01-05 10:02:44 -05:00
|
|
|
this.listeners[type] = [];
|
|
|
|
}
|
|
|
|
if (listener !== null) {
|
|
|
|
this.listeners[type].push(listener);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public removeEventListener(
|
|
|
|
type: string,
|
|
|
|
callback: domTypes.EventListenerOrEventListenerObject | null,
|
2019-03-09 12:30:38 -05:00
|
|
|
_options?: domTypes.EventListenerOptions | boolean
|
2019-01-05 10:02:44 -05:00
|
|
|
): void {
|
2019-03-30 13:40:03 -04:00
|
|
|
requiredArguments("EventTarget.removeEventListener", arguments.length, 2);
|
2019-03-30 08:18:19 -04:00
|
|
|
if (this.listeners.hasOwnProperty(type) && callback !== null) {
|
2019-01-05 10:02:44 -05:00
|
|
|
this.listeners[type] = this.listeners[type].filter(
|
|
|
|
listener => listener !== callback
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public dispatchEvent(event: domTypes.Event): boolean {
|
2019-03-30 13:40:03 -04:00
|
|
|
requiredArguments("EventTarget.dispatchEvent", arguments.length, 1);
|
2019-03-30 08:18:19 -04:00
|
|
|
if (!this.listeners.hasOwnProperty(event.type)) {
|
2019-01-05 10:02:44 -05:00
|
|
|
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;
|
|
|
|
}
|
2019-04-03 08:41:05 -04:00
|
|
|
|
|
|
|
get [Symbol.toStringTag](): string {
|
|
|
|
return "EventTarget";
|
|
|
|
}
|
2019-01-05 10:02:44 -05:00
|
|
|
}
|