Skip to content

Commit

Permalink
Merge pull request #134 from preactjs/svelte
Browse files Browse the repository at this point in the history
Add support for Svelte
  • Loading branch information
marvinhagemeister committed Sep 13, 2022
2 parents dbf905f + bc0080c commit 5a1d5d0
Show file tree
Hide file tree
Showing 4 changed files with 33 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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ npm install @preact/signals-core
npm install @preact/signals
# If you're using React
npm install @preact/signals-react
# If you're using Svelte
npm install @preact/signals-core
```

- [Guide / API](#guide--api)
Expand Down
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 5a1d5d0

Please sign in to comment.