mirror of
https://github.com/misode/misode.github.io.git
synced 2026-04-27 16:58:46 +00:00
Update model and add invalidated cycle
This commit is contained in:
@@ -1,12 +1,39 @@
|
||||
import { RootNode } from "../nodes/RootNode"
|
||||
import { Path } from "./Path"
|
||||
|
||||
export interface ModelListener {
|
||||
invalidated(model: DataModel): void
|
||||
}
|
||||
|
||||
export class DataModel {
|
||||
data: any
|
||||
schema: RootNode
|
||||
listeners: ModelListener[]
|
||||
|
||||
constructor(schema: RootNode) {
|
||||
this.schema = schema
|
||||
this.data = schema.default
|
||||
this.listeners = []
|
||||
}
|
||||
|
||||
addListener(listener: ModelListener) {
|
||||
this.listeners.push(listener)
|
||||
}
|
||||
|
||||
invalidate() {
|
||||
this.listeners.forEach(listener => listener.invalidated(this))
|
||||
}
|
||||
|
||||
set(path: Path, value: any) {
|
||||
let node = this.data;
|
||||
for (let index of path.pop()) {
|
||||
if (node[index] === undefined) {
|
||||
node[index] = {}
|
||||
}
|
||||
node = node[index]
|
||||
}
|
||||
node[path.last()] = value
|
||||
|
||||
this.invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
type PathElement = (string | number)
|
||||
|
||||
export class Path {
|
||||
export class Path implements Iterable<PathElement> {
|
||||
private arr: PathElement[]
|
||||
|
||||
constructor(arr?: PathElement[]) {
|
||||
@@ -23,4 +23,14 @@ export class Path {
|
||||
copy(): Path {
|
||||
return new Path([...this.arr])
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return `[${this.arr.map(e => e.toString()).join(', ')}]`
|
||||
}
|
||||
|
||||
*[Symbol.iterator]() {
|
||||
for (const e of this.arr) {
|
||||
yield e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user