Refactor the controller a little bit

This commit is contained in:
Kevin McConnell
2025-02-28 15:12:10 +00:00
parent a7cde91a10
commit 06dcb11e4b
@@ -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
}
}))
}
}
}
}