Skip to content

Instantly share code, notes, and snippets.

@ksnabb
Created December 14, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksnabb/271f4a7367b4f5571571c9a7a7ea6ecf to your computer and use it in GitHub Desktop.
Save ksnabb/271f4a7367b4f5571571c9a7a7ea6ecf to your computer and use it in GitHub Desktop.
Simple Javascript/HTML Counter
function pubSub() {
const listeners = [];
return {
dispatch: (event) => listeners.forEach((l) => l(event)),
subscribe: (fun) => listeners.push(fun)
}
}
function state(initialValue, pubsub) {
let val = initialValue;
function setValue(newValue) {
val = newValue;
pubsub.dispatch(newValue);
}
function getValue() {
return val;
}
return {
getValue,
setValue
}
}
const button = document.querySelector('.app button');
const showState = document.querySelector('.app p');
const appEvents = pubSub();
const appState = state(0, appEvents);
button.addEventListener('click', () => {
appState.setValue(appState.getValue() + 1);
});
appEvents.subscribe((newValue) => {
showState.innerText = `The number is now ${newValue}`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment