@surface/custom-element
Version:
Provides support of directives and data binding on custom elements.
45 lines (44 loc) • 1.94 kB
JavaScript
import { CancellationTokenSource } from "@surface/core";
import { scheduler } from "../../singletons.js";
import observe from "../observe.js";
export default class ChoiceStatement {
constructor(context) {
this.context = context;
this.cancellationTokenSource = new CancellationTokenSource();
this.subscriptions = [];
this.currentDisposable = null;
this.disposed = false;
this.task = () => {
for (const branch of this.context.branches) {
if (branch.expression(this.context.scope)) {
if (branch != this.currentBranch) {
this.currentBranch = branch;
this.currentDisposable?.dispose();
this.context.block.clear();
const [content, activator] = branch.factory();
this.context.block.setContent(content);
this.currentDisposable = activator(this.context.parent, this.context.host, this.context.scope, this.context.directives);
}
return;
}
}
this.currentDisposable?.dispose();
this.context.block.clear();
this.currentBranch = undefined;
};
const listener = () => void scheduler.enqueue(this.task, "normal", this.cancellationTokenSource.token);
for (const branch of this.context.branches) {
this.subscriptions.push(observe(context.scope, branch.observables, () => listener(), true));
}
listener();
}
dispose() {
if (!this.disposed) {
this.cancellationTokenSource.cancel();
this.currentDisposable?.dispose();
this.subscriptions.forEach(x => x.unsubscribe());
this.context.block.dispose();
this.disposed = true;
}
}
}