Skip to content

Commit

Permalink
supporting custom events
Browse files Browse the repository at this point in the history
  • Loading branch information
Sceat committed May 5, 2020
1 parent 20ce7db commit c8e941c
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions lib/event-target.js
Expand Up @@ -111,47 +111,51 @@ const EventTarget = {
*
* @param {String} method A string representing the event type to listen for
* @param {Function} listener The listener to add
* @param {Object} [options] An options object specifies characteristics about the event listener
* @param {Object} [options] An options object specifies characteristics
* about the event listener
* @public
*/
addEventListener(method, listener, options = {}) {
if (typeof listener !== 'function') return;
const { once } = options;

function onMessage(data) {
listener.call(this, new MessageEvent(data, this));
if(once) this.removeListener(method, listener);
}

function onClose(code, message) {
listener.call(this, new CloseEvent(code, message, this));
if(once) this.removeListener(method, listener);
}

function onError(error) {
listener.call(this, new ErrorEvent(error, this));
if(once) this.removeListener(method, listener);
}

function onOpen() {
listener.call(this, new OpenEvent(this));
if(once) this.removeListener(method, listener);
}

if (method === 'message') {
onMessage._listener = listener;
this.on(method, onMessage);
} else if (method === 'close') {
onClose._listener = listener;
this.on(method, onClose);
} else if (method === 'error') {
onError._listener = listener;
this.on(method, onError);
} else if (method === 'open') {
onOpen._listener = listener;
this.on(method, onOpen);
} else {
this.on(method, listener);
const type = options.once ? 'once' : 'on';

switch (method) {
case 'message':
onMessage._listener = listener;
this[type](method, onMessage);
break;
case 'close':
onClose._listener = listener;
this[type](method, onClose);
break;
case 'error':
onError._listener = listener;
this[type](method, onError);
break;
case 'open':
onOpen._listener = listener;
this[type](method, onOpen);
break;
default:
this[type](method, listener);
break;
}
},

Expand Down

0 comments on commit c8e941c

Please sign in to comment.