This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EventTarget { | |
constructor(options) { | |
if(options) { | |
Object.assign(this, options); | |
} | |
this.listeners = {}; | |
} | |
addEventListener (type, callback, useCaptureOptions) { | |
if (!(type in this.listeners)) { | |
this.listeners[type] = []; | |
} | |
this.listeners[type].push([callback, useCaptureOptions]); | |
return this.removeEventListener.bind(this, type, callback, useCaptureOptions); | |
}; | |
removeEventListener(type, callback, useCaptureOptions) { | |
if (!(type in this.listeners)) { | |
return; | |
} | |
var stack = this.listeners[type]; | |
for (let cbsarr of stack) { | |
const [cb, uco] = cbsarr; | |
if (cb === callback){ | |
const useCaptureOptionsKeys = Object.keys(useCaptureOptions); | |
const ucoKeys = Object.keys(uco); | |
if(useCaptureOptionsKeys.length === ucoKeys.length && | |
useCaptureOptionsKeys.every(k => useCaptureOptionsKeys[k] === ucoKeys[k])) { | |
stack.splice(i, 1); | |
return; | |
} | |
} | |
} | |
}; | |
dispatchEvent(event) { | |
if (!(event.type in this.listeners)) { | |
return true; | |
} | |
const stack = this.listeners[event.type].slice(); | |
for (let [cb, useCaptureOptions = {}] of stack) { | |
const { capture = (useCaptureOptions === true), once = false, passive = false } = useCaptureOptions; | |
cb.call(this, event, { | |
capture, | |
once, | |
passive | |
}); | |
if(once) { | |
this.removeEventListener(event.type, cb, useCaptureOptions); | |
} | |
} | |
return !event.defaultPrevented; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment