Я пытаюсь имитировать поведение 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
Форум по Javascript
1753669084
Anonymous
Я пытаюсь имитировать поведение 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')
Подробнее здесь: [url]https://stackoverflow.com/questions/79716826/value-setter-for-a-custom-select-element-with-lazy-loading[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия