pragma-views2
Version:
97 lines (73 loc) • 2.7 kB
JavaScript
import { BaseElement } from "../../lib/base-element.js";
import { ViewBase } from "../../lib/view-base.js";
import { loadTemplate, loadModule } from "../../lib/component-loader.js";
import { ViewBinding } from "../../lib/binding/view-binding.js";
import { releaseElements } from "../../lib/binding/binding-helpers.js";
import { observe } from "../../lib/binding/observers.js";
class ViewContainer extends BaseElement {
static get observedAttributes() {
return ["view"];
}
disconnectedCallback() {
this._unloadCurrentView();
}
async viewChanged(newValue) {
this._unloadCurrentView();
if ((newValue || "").length == 0) {
return;
}
this.viewName = newValue;
const path = `/app/views/${newValue}/${newValue}`;
return this._loadView(path, newValue);
}
async _loadView(path) {
const jsFile = `${path}.js`;
const htmlFile = `${path}.html`;
const module = await loadModule(jsFile, this.viewName);
this.viewModel = observe(new module.default());
const template = await loadTemplate(htmlFile);
const viewInstance = document.importNode(template, true);
if (this.viewModel instanceof ViewBase) {
this.binding = new ViewBinding(this.viewModel);
await this.binding.parse(viewInstance);
}
this.appendChild(viewInstance);
if (this.binding != undefined) {
this.binding.observeDomChanged();
}
if (this.viewModel.connectedCallback) {
this.viewModel.connectedCallback();
}
}
async showView(viewName, loadedCallback) {
await this.viewChanged(viewName);
if (loadedCallback != undefined) {
loadedCallback();
}
}
_unloadCurrentView() {
this._disposeView();
if (window.modules != undefined) {
window.modules.delete(this.viewName);
}
while (this.firstChild) {
this.removeChild(this.firstChild);
}
}
_disposeView() {
releaseElements(this.children);
if (this.viewModel == undefined) return;
if (this.viewModel.disconnectedCallback) {
this.viewModel.disconnectedCallback();
}
if (this.binding != undefined) {
this.binding.dispose();
this.binding = null;
}
if (this.viewModel.dispose != undefined) {
this.viewModel.dispose();
}
this.viewModel = null;
}
}
customElements.define("view-container", ViewContainer);