Skip to content

Instantly share code, notes, and snippets.

@Zyclotrop-j
Last active November 21, 2021 06:05
Embed
What would you like to do?
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