|
- 'use strict';
-
-
- class Event {
-
-
- constructor(type, target) {
- this.target = target;
- this.type = type;
- }
- }
-
-
- class MessageEvent extends Event {
-
-
- constructor(data, target) {
- super('message', target);
-
- this.data = data;
- }
- }
-
-
- class CloseEvent extends Event {
-
-
- constructor(code, reason, target) {
- super('close', target);
-
- this.wasClean = target._closeFrameReceived && target._closeFrameSent;
- this.reason = reason;
- this.code = code;
- }
- }
-
-
- class OpenEvent extends Event {
-
-
- constructor(target) {
- super('open', target);
- }
- }
-
-
- class ErrorEvent extends Event {
-
-
- constructor(error, target) {
- super('error', target);
-
- this.message = error.message;
- this.error = error;
- }
- }
-
-
- const EventTarget = {
-
-
- addEventListener(type, listener, options) {
- if (typeof listener !== 'function') return;
-
- function onMessage(data) {
- listener.call(this, new MessageEvent(data, this));
- }
-
- function onClose(code, message) {
- listener.call(this, new CloseEvent(code, message, this));
- }
-
- function onError(error) {
- listener.call(this, new ErrorEvent(error, this));
- }
-
- function onOpen() {
- listener.call(this, new OpenEvent(this));
- }
-
- const method = options && options.once ? 'once' : 'on';
-
- if (type === 'message') {
- onMessage._listener = listener;
- this[method](type, onMessage);
- } else if (type === 'close') {
- onClose._listener = listener;
- this[method](type, onClose);
- } else if (type === 'error') {
- onError._listener = listener;
- this[method](type, onError);
- } else if (type === 'open') {
- onOpen._listener = listener;
- this[method](type, onOpen);
- } else {
- this[method](type, listener);
- }
- },
-
-
-
- removeEventListener(type, listener) {
- const listeners = this.listeners(type);
-
- for (let i = 0; i < listeners.length; i++) {
- if (listeners[i] === listener || listeners[i]._listener === listener) {
- this.removeListener(type, listeners[i]);
- }
- }
- }
- };
-
- module.exports = EventTarget;
|