Created
March 13, 2020 13:56
-
-
Save WebReflection/6c459f306be258f4b7a92706f3435ffa to your computer and use it in GitHub Desktop.
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 Signal extends EventTarget { | |
#aborted = false; | |
#controller = null; | |
constructor(controller) { | |
super(); | |
this.#controller = controller; | |
this.addEventListener('abort', this); | |
} | |
handleEvent(event) { | |
if (event.detail !== this.#controller) | |
event.stopImmediatePropagation(); | |
else | |
this.#aborted = true; | |
} | |
get aborted() { | |
return this.#aborted; | |
} | |
} | |
class Controller { | |
constructor() { | |
this.signal = new Signal(this); | |
} | |
abort() { | |
this.signal.dispatchEvent(new CustomEvent('abort', {detail: this})); | |
} | |
} | |
const contr = new Controller; | |
const {signal} = contr; | |
signal.addEventListener('abort', console.log); | |
signal.dispatchEvent(new Event('abort')); // nope | |
contr.abort(); // yup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment