Last active
March 13, 2020 15:37
-
-
Save WebReflection/aadbbeee956567a1eeb06c0f2de86c4d 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; | |
constructor(controller) { | |
super(); | |
// one of those cases where unreachable listener | |
// is actually desired 'cause it's more secure | |
this.addEventListener('abort', event => { | |
if (event.detail !== 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 | |
console.log(signal.aborted); // false | |
// only the signal owner can make it abort 👍 | |
contr.abort(); // yup | |
console.log(signal.aborted); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment