Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created August 24, 2020 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodydavis/db6efdac04a1a9a039b939436373fc63 to your computer and use it in GitHub Desktop.
Save rodydavis/db6efdac04a1a9a039b939436373fc63 to your computer and use it in GitHub Desktop.
const Consumer = (Base: any) =>
class extends Base {
requestInstance = (key: any) => {
const event = new CustomEvent("request-instance", {
detail: {key} as any,
bubbles: true,
cancelable: true,
});
this.dispatchEvent(event);
return event.detail.instance;
};
};
const Provider = (Base: any) =>
class extends Base {
_instances = new Map();
constructor() {
super();
this.addEventListener("request-instance", (event: CustomEvent) => {
const key = event.detail.key;
if (this._instances.has(key)) {
event.detail.instance = this._instances.get(key);
event.stopPropagation();
}
});
}
provideInstance = (key: string, instance: any) => {
this._instances.set(key, instance);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment