Skip to content

Commit

Permalink
refactor(core): optimize watch decorator and fix prop handling
Browse files Browse the repository at this point in the history
- Update watch decorator to use a dedicated WatchCallback type
- Refactor doWatch function to use WatchCallback instead of watchMethodName
- Fix typo in handleProps function name
  • Loading branch information
star-ll committed Nov 16, 2024
1 parent 43500a1 commit b8e6aa4
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
4 changes: 3 additions & 1 deletion packages/core/src/decorators/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,9 @@ function getCustomElementWrapper(target: any, { tag, style, observedAttributes }
warn(`invalid watchKey ${watchKey}`);
return;
}
doWatch(this, watchMethodName, ctx, property, statePool, item.options);

const watchCallback = this[watchMethodName];
doWatch(this, watchCallback, ctx, property, statePool, item.options);
});
}
}
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/decorators/Watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface WatchOptions {
immediate?: boolean;
}

export type WatchCallback<T = unknown> = (value?: T, oldValue?: T, cleanup?: () => void) => void;

// todo: validate watchKeys
// todo: watchKeys param support ‘obj.s.a’
// todo: pre / sync / post
Expand All @@ -22,7 +24,7 @@ export default function Watch(watchKeys: any[] | never[], options: WatchOptions

export function doWatch(
instance: DecoWebComponent,
watchMethodName: keyof DecoWebComponent,
watchCallback: WatchCallback,
propertyCtx: any,
property: string | symbol,
statePool: StatePool,
Expand All @@ -37,7 +39,7 @@ export function doWatch(
statePool.delete(propertyCtx, property, watchEffect);
};

instance[watchMethodName].call(instance, newValue, oldValue, cleanup);
watchCallback.call(instance, newValue, oldValue, cleanup);

oldValue = newValue;

Expand Down
6 changes: 3 additions & 3 deletions packages/renderer/src/patch/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,19 +109,19 @@ export function patchProps(element: HTMLElement, props: Props, oldProps: Props)
if (!['key', 'children'].includes(propName)) {
const value = props[propName];

handlePros(element, propName, props, value);
handleProps(element, propName, props, value);
handledProps.add(propName);
}
}

for (const propName of Object.keys(oldProps)) {
if (!handledProps.has(propName)) {
handlePros(element, propName, oldProps, undefined);
handleProps(element, propName, oldProps, undefined);
}
}
}

export function handlePros(element: HTMLElement, propName: string, props: Props, value: any) {
export function handleProps(element: HTMLElement, propName: string, props: Props, value: any) {
try {
switch (propName) {
case 'dangerouslySetInnerHTML':
Expand Down

0 comments on commit b8e6aa4

Please sign in to comment.