Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Svelte #134

Merged
merged 1 commit into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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