@joist/di
Version:
Dependency Injection for Vanilla JS classes
35 lines • 1.25 kB
JavaScript
import { INJECTOR_CTX } from "../context/injector.js";
import { ContextRequestEvent, } from "../context/protocol.js";
import { Injector } from "../injector.js";
export class DOMInjector extends Injector {
#element = null;
#controller = null;
get isAttached() {
return this.#element !== null && this.#controller !== null;
}
attach(element) {
if (this.isAttached) {
throw new Error(`This DOMInjector is already attached to ${this.#element}. Detach first before attaching again`);
}
this.#element = element;
this.#controller = new AbortController();
this.#element.addEventListener("context-request", (e) => {
if (e.context === INJECTOR_CTX) {
if (e.target !== element) {
e.stopPropagation();
e.callback(this);
}
}
}, { signal: this.#controller.signal });
this.#element.dispatchEvent(new ContextRequestEvent(INJECTOR_CTX, (parent) => {
this.parent = parent;
}));
}
detach() {
if (this.#controller) {
this.#controller.abort();
}
this.#element = null;
}
}
//# sourceMappingURL=dom-injector.js.map