Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active March 13, 2020 15:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/aadbbeee956567a1eeb06c0f2de86c4d to your computer and use it in GitHub Desktop.
Save WebReflection/aadbbeee956567a1eeb06c0f2de86c4d to your computer and use it in GitHub Desktop.
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