Skip to content

Commit

Permalink
docs: improve under the hood explanation
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed May 14, 2024
1 parent 9d62ada commit c70a754
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,17 @@ We utilize JavaScript's call stack to keep track of the dependencies of each eff
Whenever a Signal is read inside an effect, we add the effect to the Signal's list of subscribers, and whenever the Signal is written to, we notify all the subscribers to run their effects:

```typescript
let currentEffect = null;

function createEffect(cb) {
callStack.add(cb);
currentEffect = cb;

// This will trigger the Signal's `get` method, which in turn,
// will add the effect to the Signal's subscribers list.
// This will trigger the `get` method of any Signal that's
// being accessed inside the effect, which in turn,
// add the effect to the Signal's subscribers list.
cb();

callStack.delete(cb);
currentEffect = null;
}

function createSignal() {
Expand All @@ -142,15 +145,15 @@ function createSignal() {
subscribers: new Set(),

get() {
// Merge `this.subscribers` with the current call stack.
this.subscribers.add(currentEffect);

return this.value;
},

set(newValue) {
this.value = newValue;

// Notify all the subscribers in `this.subscribers`.
this.subscribers.forEach((effect) => effect());
},
};

Expand Down

0 comments on commit c70a754

Please # to comment.