diff --git a/web/static/numerus.js b/web/static/numerus.js index 86b7c23..c0ab0cb 100644 --- a/web/static/numerus.js +++ b/web/static/numerus.js @@ -4,9 +4,13 @@ class Multiselect extends HTMLDivElement { this.initialized = false; this.toSearch = ''; this.highlighted = 0; + this.onFocusOutHandler = this.onFocusOut.bind(this); } connectedCallback() { + if (!this.isConnected) { + return; + } if (!this.initialized) { for (const child of this.children) { switch (child.nodeName) { @@ -22,6 +26,19 @@ class Multiselect extends HTMLDivElement { this.init(); } } + window.addEventListener('focusin', this.onFocusOutHandler); + document.addEventListener('click', this.onFocusOutHandler); + } + + disconnectedCallback() { + document.removeEventListener('click', this.onFocusOutHandler); + window.removeEventListener('focusin', this.onFocusOutHandler); + } + + onFocusOut(e) { + if (this.contains(e.target)) return; + if (!e.target.isConnected) return; + this.close(); } init() { @@ -93,17 +110,6 @@ class Multiselect extends HTMLDivElement { this.options.setAttribute('role', 'listbox'); this.close(); - window.addEventListener('focusin', (e) => { - if (this.contains(e.target)) return; - this.close(); - }); - - document.addEventListener('click', (e) => { - if (this.contains(e.target)) return; - if (!e.target.isConnected) return; - this.close(); - }); - this.rebuild(); } @@ -278,9 +284,13 @@ class Tags extends HTMLDivElement { super(); this.initialized = false; this.tags = []; + this.onFocusOutHandler = this.onFocusOut.bind(this); } connectedCallback() { + if (!this.isConnected) { + return; + } if (!this.initialized) { for (const child of this.children) { switch (child.nodeName) { @@ -296,6 +306,18 @@ class Tags extends HTMLDivElement { this.init(); } } + window.addEventListener('focusin', this.onFocusOutHandler); + } + + disconnectedCallback() { + window.removeEventListener('focusin', this.onFocusOutHandler); + } + + onFocusOut(e) { + if (this.contains(e.target)) return; + if (e.target.value && e.target.value.trim() !== '') { + this.createTag(); + } } init() { @@ -339,12 +361,6 @@ class Tags extends HTMLDivElement { break; } }); - window.addEventListener('focusin', (e) => { - if (this.contains(e.target)) return; - if (e.target.value.trim() !== '') { - this.createTag(); - } - }); // Must come after the search input this.tagList.append(this.label);