Я пытаюсь имитировать поведение htmlSelectelement value для работы в любое время, но также сохраняю ленивую загрузку моих пользовательских элементов. Я использую базовый класс, который кэш-элементы одного и того же типа, чтобы предотвратить загрузку их шаблона несколько раз: < /p>
const templateCache = new Map();
export class DSElement extends HTMLElement {
constructor() {
super();
this._name = this.constructor._type;
this.attachShadow({ mode: 'open' });
this._internals = this.attachInternals();
}
async connectedCallback() {
let template = templateCache.get(this._name);
if (!template) {
const templateUrl =
chrome.runtime.getURL(`interface/templates/${this._name}.html`);
const response = await fetch(templateUrl);
const html = await response.text();
const wrapper = document.createElement('template');
wrapper.innerHTML = html;
const inner = wrapper.content.getElementById(`${this._name}-template`);
if (inner) {
template = inner;
templateCache.set(this._name, template);
}
requestAnimationFrame(() => this._after());
}
if (template)
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
async _after() {
// Virtual method
}
}
Затем я создаю класс dsselect , который обрабатывает рисование материала внутри _after Метод:
import { DSElement } from './ds-element.js';
class DSSelect extends DSElement {
static _type = 'ds-select';
constructor() {
super();
this._value = null;
this._firstOption = null;
this._label = null;
this._internals.role = 'select';
}
async _after() {
this._select = this.shadowRoot.getElementById('select');
this._options = this.shadowRoot.getElementById('options');
this._labelSpan = this.shadowRoot.getElementById('label');
this.setInitialSelection();
this._select.addEventListener('click', () => this.toggle());
this.addEventListener('click', e => this.handleOptionClick(e));
}
setInitialSelection() {
let firstOption;
if (this._firstOption !== null)
firstOption = this._firstOption;
else
firstOption = this.querySelector('ds-opt');
if (firstOption)
this.selectOption(firstOption);
}
selectOption(option) {
this._value = option.getAttribute('value');
this._label = option.textContent;
this._labelSpan.innerText = this._label;
this.dispatchEvent(new Event('change', {bubbles: true}));
}
get value() {
return this._value;
}
set value(value) {
const match = Array.from(this.querySelectorAll('ds-opt')).find(
opt => opt.getAttribute('value') === value
);
if (match)
this._firstOption = match;
}
}
customElements.define(
DSSelect._type, DSSelect
);
И где -то в моем коде я использую Setter on domcontentloaded Событие:
const reloadOptions = () => {
const elMode = document.getElementById('mode');
elMode.value = 'selected';
};
document.addEventListener('DOMContentLoaded', reloadOptions);
< /code>
Это на самом деле работает в 99% случаев, пока я не удерживаю F5, чтобы быстро перезагрузить много раз. Я думаю, что между ReloadOptions и _after и this.queryselectorall ('ds-opt')
Подробнее здесь: https://stackoverflow.com/questions/797 ... zy-loading
Установка значений для пользовательского элемента выбора с ленивой загрузкой ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение