Skip to content

Instantly share code, notes, and snippets.

@doug
Last active February 5, 2017 22:23
Show Gist options
  • Save doug/c354a31b52304933d776701e9591a659 to your computer and use it in GitHub Desktop.
Save doug/c354a31b52304933d776701e9591a659 to your computer and use it in GitHub Desktop.
const provider = Symbol();
export function provide(key: symbol, value: any, ctx?: HTMLElement) {
const node: any = ctx || document.body;
let providers = node[provider];
if (!providers) {
node[provider] = providers = {};
node.addEventListener('di-provider', (event: CustomEvent) => {
event.detail.provider = providers[event.detail.key];
event.preventDefault();
event.stopPropagation();
});
}
providers[key] = value;
}
export function acquire(key: symbol, ctx?: HTMLElement) {
ctx = ctx || document.body;
let event = new CustomEvent('di-provider', {
detail: {key},
bubbles: true,
cancelable: true,
composed: true,
});
ctx.dispatchEvent(event);
if (event.defaultPrevented) {
return event.detail.provider;
} else {
throw new Error(`No provider found for ${key.toString()}.`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment