Skip to content

Commit

Permalink
feat(effect): handle nested effects
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsoncodehk committed Oct 5, 2024
1 parent 827737a commit 2e608ff
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion lib/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function effect(fn: () => void) {
}

export class Effect implements IEffect, Subscriber {
scope = currentEffectScope;
nextNotify = undefined;

// Subscriber
Expand All @@ -32,7 +33,12 @@ export class Effect implements IEffect, Subscriber {

run() {
const lastActiveSub = Subscriber.startTrack(this);
this.fn();
if (this.scope !== undefined) {
this.scope.run(this.fn);
}
else {
this.fn();
}
Subscriber.endTrack(this, lastActiveSub);
}
}
4 changes: 2 additions & 2 deletions lib/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ export class EffectScope {
subs: Subscriber[] = [];

run<T>(fn: () => T) {
const original = currentEffectScope;
const lastEffectScope = currentEffectScope;
try {
currentEffectScope = this;
return fn();
} finally {
currentEffectScope = original;
currentEffectScope = lastEffectScope;
}
}

Expand Down

0 comments on commit 2e608ff

Please sign in to comment.