Skip to content

Commit 5a1d5d0

Browse files
Merge pull request #134 from preactjs/svelte
Add support for Svelte
2 parents dbf905f + bc0080c commit 5a1d5d0

File tree

4 files changed

+33
-0
lines changed

4 files changed

+33
-0
lines changed

.changeset/large-news-report.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@preact/signals-core": minor
3+
---
4+
5+
Add `.subscribe()`-method to signals to add support for natively using signals with Svelte

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ npm install @preact/signals-core
1717
npm install @preact/signals
1818
# If you're using React
1919
npm install @preact/signals-react
20+
# If you're using Svelte
21+
npm install @preact/signals-core
2022
```
2123

2224
- [Guide / API](#guide--api)

packages/core/src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ export class Signal<T = any> {
123123
};
124124
}
125125

126+
subscribe(fn: (value: T) => () => void) {
127+
return effect(() => fn(this.value));
128+
}
129+
126130
/**
127131
* A custom update routine to run when this Signal's value changes.
128132
* @internal

packages/core/test/signal.test.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,28 @@ describe("signal", () => {
4747
expect(b.peek()).to.equal(2);
4848
});
4949
});
50+
51+
describe(".subscribe()", () => {
52+
it("should subscribe to a signal", () => {
53+
const spy = sinon.spy();
54+
const a = signal(1);
55+
56+
a.subscribe(spy);
57+
expect(spy).to.be.calledWith(1);
58+
});
59+
60+
it("should unsubscribe from a signal", () => {
61+
const spy = sinon.spy();
62+
const a = signal(1);
63+
64+
const dispose = a.subscribe(spy);
65+
dispose();
66+
spy.resetHistory();
67+
68+
a.value = 2;
69+
expect(spy).not.to.be.called;
70+
});
71+
});
5072
});
5173

5274
describe("effect()", () => {

0 commit comments

Comments
 (0)