diff --git a/buildoz.js b/buildoz.js index a145260..37b02c4 100644 --- a/buildoz.js +++ b/buildoz.js @@ -40,6 +40,7 @@ class Buildoz extends HTMLElement { class BZselect extends Buildoz { #value + #fillFromMarkup = true constructor(){ super() @@ -58,9 +59,12 @@ class BZselect extends Buildoz { this.prepend(this.button) this.button.addEventListener('click', this.toggle.bind(this)) this.options = this.querySelectorAll('option') - for(const opt of this.options){ - opt.addEventListener('click', this.onClick.bind(this)) - if(opt.getAttribute('selected') !== null) this.onOption(opt.value, true) + if(this.#fillFromMarkup){ //can only do it once and only if fillOptions was not already called !! + for(const opt of this.options){ + opt.addEventListener('click', this.onClick.bind(this)) + if(opt.getAttribute('selected') !== null) this.onOption(opt.value, true) + } + this.#fillFromMarkup = false } } @@ -88,7 +92,7 @@ class BZselect extends Buildoz { } } - toggle(){ + toggle(){ for(const opt of this.options){ if(this.open) opt.classList.remove('open') else opt.classList.add('open') @@ -96,7 +100,7 @@ class BZselect extends Buildoz { this.open = !this.open } - onClick(evt){ + onClick(evt){ const opt = evt.target.closest('option') if(opt && opt.value) this.onOption(opt.value) } @@ -108,17 +112,20 @@ class BZselect extends Buildoz { } addOption(value, markup){ + // Caution: you can count on connectedCallback to have run already, because one might fill before adding to the DOM const opt = document.createElement('option') opt.setAttribute('value', value) opt.innerHTML = markup opt.addEventListener('click',this.onClick.bind(this)) this.append(opt) this.options = this.querySelectorAll('option') + this.#fillFromMarkup = false } fillOptions(opts, erase = true){ + // Caution: you can count on connectedCallback to have run already, because one might fill before adding to the DOM if(erase){ - //this.options = this.querySelectorAll('option') + this.options = this.querySelectorAll('option') this.options.forEach(node => { node.remove() }) this.options = this.querySelectorAll('option') this.onOption('', true) // unselect last