mirror of
https://github.com/misode/misode.github.io.git
synced 2026-04-26 08:26:51 +00:00
Complete refactor (#123)
This commit is contained in:
14
src/app/state/LocalStorageProperty.ts
Normal file
14
src/app/state/LocalStorageProperty.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Property } from './Property'
|
||||
|
||||
export class LocalStorageProperty extends Property<string> {
|
||||
constructor(private id: string, fallback: string) {
|
||||
super(localStorage.getItem(id) ?? fallback)
|
||||
}
|
||||
set(value: string) {
|
||||
super.set(value)
|
||||
localStorage.setItem(this.id, value)
|
||||
}
|
||||
get(): string {
|
||||
return this.value
|
||||
}
|
||||
}
|
||||
40
src/app/state/Property.ts
Normal file
40
src/app/state/Property.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { hexId } from "../Utils"
|
||||
|
||||
type PropertyWatcher<T> = (value: T, oldValue: T | null) => void
|
||||
type NamedPropertyWatcher<T> = {
|
||||
name: string
|
||||
watcher: PropertyWatcher<T>
|
||||
}
|
||||
|
||||
export class Property<T> {
|
||||
private watchers: NamedPropertyWatcher<T>[] = []
|
||||
|
||||
constructor(public value: T) {}
|
||||
|
||||
set(value: T) {
|
||||
if (this.value === value) return
|
||||
const oldValue = this.value
|
||||
this.value = value
|
||||
this.watchers.forEach(w => w.watcher(this.value, oldValue))
|
||||
}
|
||||
|
||||
get(): T {
|
||||
return this.value
|
||||
}
|
||||
|
||||
watchRun(watcher: PropertyWatcher<T>, name?: string) {
|
||||
watcher(this.value, null)
|
||||
return this.watch(watcher, name)
|
||||
}
|
||||
|
||||
watch(watcher: PropertyWatcher<T>, name?: string) {
|
||||
name = name ?? hexId()
|
||||
const w = this.watchers.find(w => w.name === name)
|
||||
if (w) {
|
||||
w.watcher = watcher
|
||||
} else {
|
||||
this.watchers.push({ name, watcher })
|
||||
}
|
||||
return this
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user