Last active
June 12, 2024 23:00
-
-
Save joshuaalpuerto/a2459de67c3991d600acbc02c955676c to your computer and use it in GitHub Desktop.
This gist contains a simple implementation of the Signal and Effect pattern in JavaScript. The Signal pattern is a behavioral design pattern that allows communication between objects in a decoupled way, while the Effect pattern is a pattern that allows for the separation of side effects from the main logic of an application.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let currentListener = undefined; | |
function createSignal(initialValue) { | |
let value = initialValue; | |
const subscribers = new Set(); | |
const read = () => { | |
if (currentListener !== undefined) { | |
subscribers.add(currentListener); | |
} | |
return value; | |
}; | |
const write = (newValue) => { | |
value = newValue; | |
subscribers.forEach((fn) => fn()); | |
}; | |
return [read, write]; | |
} | |
function createEffect(callback) { | |
currentListener = callback; | |
// we call the callback so we start registering this listener to subscribers | |
callback(); | |
currentListener = undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage