Skip to content

Commit

Permalink
Merge pull request #527 from jviide/sub2
Browse files Browse the repository at this point in the history
refactor: inline Signal.prototype.subscribe implementation
  • Loading branch information
marvinhagemeister authored Mar 14, 2024
2 parents 089b3fd + 9444f79 commit dc0f528
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,14 @@ Signal.prototype._unsubscribe = function (node) {
Signal.prototype.subscribe = function (fn) {
return effect(() => {
const value = this.value;
untracked(() => fn(value));

const prevContext = evalContext;
evalContext = undefined;
try {
fn(value);
} finally {
evalContext = prevContext;
}
});
};

Expand Down
10 changes: 10 additions & 0 deletions packages/core/test/signal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ describe("signal", () => {
expect(spy).to.be.calledWith(1);
});

it("should run the callback when the signal value changes", () => {
const spy = sinon.spy();
const a = signal(1);

a.subscribe(spy);

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

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

0 comments on commit dc0f528

Please sign in to comment.