Skip to content

Instantly share code, notes, and snippets.

@joshuaalpuerto
Last active June 12, 2024 23:00
Show Gist options
  • Save joshuaalpuerto/a2459de67c3991d600acbc02c955676c to your computer and use it in GitHub Desktop.
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.
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;
}
@joshuaalpuerto
Copy link
Author

Usage

const [count, setCount] = createSignal(0);

const button = document.createElement('button');
// call the effect so this will be registered 
// as a subscribers to the signal
createEffect(() => {
  // when the signal change it will call this inner function.
	button.innerText = count();
});

button.addEventListener('click', () => {
	setCount(count() + 1);
});

document.body.append(button);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment