From 06dcb11e4b14191b94db589147d7ab587e8eec7a Mon Sep 17 00:00:00 2001 From: Kevin McConnell Date: Fri, 28 Feb 2025 15:12:10 +0000 Subject: [PATCH] Refactor the controller a little bit --- .../controllers/autosave_controller.js | 48 +++++++++++-------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/app/javascript/controllers/autosave_controller.js b/app/javascript/controllers/autosave_controller.js index b863b648b..aaea8fa87 100644 --- a/app/javascript/controllers/autosave_controller.js +++ b/app/javascript/controllers/autosave_controller.js @@ -4,47 +4,53 @@ import { debounce } from "helpers/timing_helpers" export default class extends Controller { static targets = ["input"] static values = { key: String } - + initialize() { - this.debouncedSave = debounce(() => { - const content = this.inputTarget.value - if (content) { - localStorage.setItem(this.keyValue, content) - } else { - this.clear() - } - }, 300) + this.save = debounce(this.save.bind(this), 300) } - + connect() { - this.restoreContent() + this.#restoreContent() } - + submit({ detail: { success } }) { if (success) { - this.clear() + this.#clear() } } save() { - this.debouncedSave() + const content = this.inputTarget.value + if (content) { + localStorage.setItem(this.keyValue, content) + } else { + this.#clear() + } } - - clear() { + + // Private + + #clear() { localStorage.removeItem(this.keyValue) } - - restoreContent() { + + #restoreContent() { const savedContent = localStorage.getItem(this.keyValue) if (savedContent) { this.inputTarget.value = savedContent + this.#triggerChangeEvent(savedContent) + } + } + + #triggerChangeEvent(newValue) { + if (this.inputTarget.tagName === "HOUSE-MD") { this.inputTarget.dispatchEvent(new CustomEvent('house-md:change', { bubbles: true, - detail: { + detail: { previousContent: '', - newContent: savedContent + newContent: newValue } })) } } -} \ No newline at end of file +}