Skip to content

Commit

Permalink
fix: only track observed by if not same scope
Browse files Browse the repository at this point in the history
  • Loading branch information
mihar-22 committed Nov 26, 2022
1 parent 94693cd commit d609fef
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
4 changes: 3 additions & 1 deletion src/observables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,8 +465,10 @@ function adopt(node: Node) {
}

function observe(observable: Node, observer: Node) {
(observable[OBSERVED_BY] ??= new Set()).add(observer);
(observer[OBSERVING] ??= new Set()).add(observable);
if (observable[SCOPE] !== observer) {
(observable[OBSERVED_BY] ??= new Set()).add(observer);
}
}

function dirtyNode(node: Node) {
Expand Down
24 changes: 12 additions & 12 deletions tests/effect.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, observable, effect, tick, onDispose } from '../src';
import { computed, observable, effect, tick, onDispose, getScope } from '../src';

afterEach(() => tick());

Expand Down Expand Up @@ -174,39 +174,39 @@ it('should dispose of nested effect', async () => {
expect(innerEffect).not.toHaveBeenCalledWith(10);
});

it.skip('should conditionally observe', async () => {
it('should conditionally observe', async () => {
const $a = observable(0);
const $b = observable(0);
const $cond = observable(true);
const spy = vi.fn(() => ($cond() ? $a() : $b()));
const $c = computed(() => ($cond() ? $a() : $b()));
const $effect = vi.fn();

effect(() => {
spy();
$c();
$effect();
});

expect(spy).toHaveBeenCalledTimes(1);
expect($effect).toHaveBeenCalledTimes(1);

$b.set(1);
await tick();
expect(spy).toHaveBeenCalledTimes(1);
expect($effect).toHaveBeenCalledTimes(1);

$a.set(1);
await tick();
expect(spy).toHaveBeenCalledTimes(2);
expect($effect).toHaveBeenCalledTimes(2);

$cond.set(false);
await tick();
expect(spy).toHaveBeenCalledTimes(3);

spy.mockReset();
expect($effect).toHaveBeenCalledTimes(2);

$b.set(2);
await tick();
expect(spy).toHaveBeenCalledTimes(1);
expect($effect).toHaveBeenCalledTimes(3);

$a.set(2);
await tick();
expect(spy).toHaveBeenCalledTimes(1);
expect($effect).toHaveBeenCalledTimes(3);
});

it('should dispose of nested conditional effect', async () => {
Expand Down

0 comments on commit d609fef

Please sign in to comment.