From 6cc839617bfb9cbf4654bf86e41465f5c5f324fe Mon Sep 17 00:00:00 2001 From: Morgan Grubb Date: Tue, 1 Aug 2023 09:54:37 -0700 Subject: [PATCH] Use stimulus lifecycle methods for targets This is a quality-of-life improvement that makes it easier to work with stimulus-autocomplete in a dynamic environment and also easier to inherit from for additional functionality. --- src/autocomplete.js | 51 ++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/autocomplete.js b/src/autocomplete.js index efec9e0..5e1a315 100644 --- a/src/autocomplete.js +++ b/src/autocomplete.js @@ -16,40 +16,43 @@ export default class Autocomplete extends Controller { } static uniqOptionId = 0 + initialize() { + this.onInputChange = debounce(this.onInputChange, this.delayValue) + this.mouseDown = false + this.readyValue = true + } + connect() { this.close() + } - if(!this.inputTarget.hasAttribute("autocomplete")) this.inputTarget.setAttribute("autocomplete", "off") - this.inputTarget.setAttribute("spellcheck", "false") + resultsTargetConnected(target) { + target.addEventListener("mousedown", this.onResultsMouseDown) + target.addEventListener("click", this.onResultsClick) + } - this.mouseDown = false + resultsTargetDisconnected(target) { + target.removeEventListener("mousedown", this.onResultsMouseDown) + target.removeEventListener("click", this.onResultsClick) + } - this.onInputChange = debounce(this.onInputChange, this.delayValue) + inputTargetConnected(target) { + if(!target.hasAttribute("autocomplete")) target.setAttribute("autocomplete", "off") + target.setAttribute("spellcheck", "false") - this.inputTarget.addEventListener("keydown", this.onKeydown) - this.inputTarget.addEventListener("blur", this.onInputBlur) - this.inputTarget.addEventListener("input", this.onInputChange) - this.resultsTarget.addEventListener("mousedown", this.onResultsMouseDown) - this.resultsTarget.addEventListener("click", this.onResultsClick) + target.addEventListener("keydown", this.onKeydown) + target.addEventListener("blur", this.onInputBlur) + target.addEventListener("input", this.onInputChange) - if (this.inputTarget.hasAttribute("autofocus")) { - this.inputTarget.focus() + if (target.hasAttribute("autofocus")) { + target.focus() } - - this.readyValue = true } - disconnect() { - if (this.hasInputTarget) { - this.inputTarget.removeEventListener("keydown", this.onKeydown) - this.inputTarget.removeEventListener("blur", this.onInputBlur) - this.inputTarget.removeEventListener("input", this.onInputChange) - } - - if (this.hasResultsTarget) { - this.resultsTarget.removeEventListener("mousedown", this.onResultsMouseDown) - this.resultsTarget.removeEventListener("click", this.onResultsClick) - } + inputTargetDisconnected(target) { + target.removeEventListener("keydown", this.onKeydown) + target.removeEventListener("blur", this.onInputBlur) + target.removeEventListener("input", this.onInputChange) } sibling(next) {