From 9d62c64b0f059f0504aad522bddb76627945e6de Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Wed, 14 May 2025 16:13:52 +1000 Subject: [PATCH] Refactor state management in CustomElement: simplify setState and getState methods, update keyPath parameter naming for consistency --- src/main.ts | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/src/main.ts b/src/main.ts index 80c97ab..20f3f77 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,6 @@ interface CustomElement extends HTMLElement { setState(key_path: string, value: any): void + getState(key_path: string): any } interface ComponentOptions { @@ -25,8 +26,8 @@ export default (options: ComponentOptions) => { // copy state from options this._states = new Proxy({ ...(states || {}) }, { - set: (target: Record, prop: string, value: any) => { - const valueRoute = prop.split('.') + set: (target: Record, keyPath: string, value: any) => { + const valueRoute = keyPath.split('.') let currentTarget = target for (let i in valueRoute) { const key = valueRoute[i] @@ -39,13 +40,25 @@ export default (options: ComponentOptions) => { currentTarget = currentTarget[key] } } - console.log(`State updated: ${JSON.stringify(this._states)}`) // TODO: trigger dom updates // TODO: trigger state update events return true }, - get: (target: Record, prop: string) => { - return target[prop] + get: (target: Record, keyPath: string) => { + const valueRoute = keyPath.split('.') + let currentTarget = target + for (let i in valueRoute) { + const key = valueRoute[i] + if (parseInt(i) === valueRoute.length - 1) { + return currentTarget[key] + } else { + if (!currentTarget[key]) { + currentTarget[key] = {} + } + currentTarget = currentTarget[key] + } + } + return undefined } }) @@ -95,19 +108,12 @@ export default (options: ComponentOptions) => { } // state manager - setState(key_path: string, value: any) { - const valueRoute = key_path.split('.') - let currentTarget = this._states - for (let i in valueRoute) { - const key = valueRoute[i] - if (parseInt(i) === valueRoute.length - 1) { - currentTarget[key] = value - } else { - if (!currentTarget[key]) currentTarget[key] = {} - currentTarget = currentTarget[key] - } - } - console.log(`State updated: ${this._states}`) + setState(keyPath: string, value: any) { + this._states[keyPath] = value + } + + getState(keyPath: string) { + return this._states[keyPath] } }