Skip to content

Commit

Permalink
Add .subscribe- method to signals to add support for Svelte
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Sep 13, 2022
1 parent dbf905f commit 64ef7a1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/large-news-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@preact/signals-core": minor
---

Add `.subscribe()`-method to signals to add support for natively using signals with Svelte
4 changes: 4 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ export class Signal<T = any> {
};
}

subscribe(fn: (value: T) => () => void) {
return effect(() => fn(this.value));
}

/**
* A custom update routine to run when this Signal's value changes.
* @internal
Expand Down
22 changes: 22 additions & 0 deletions packages/core/test/signal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,28 @@ describe("signal", () => {
expect(b.peek()).to.equal(2);
});
});

describe(".subscribe()", () => {
it("should subscribe to a signal", () => {
const spy = sinon.spy();
const a = signal(1);

a.subscribe(spy);
expect(spy).to.be.calledWith(1);
});

it("should unsubscribe from a signal", () => {
const spy = sinon.spy();
const a = signal(1);

const dispose = a.subscribe(spy);
dispose();
spy.resetHistory();

a.value = 2;
expect(spy).not.to.be.called;
});
});
});

describe("effect()", () => {
Expand Down

0 comments on commit 64ef7a1

Please sign in to comment.