Created
December 14, 2018 20:24
-
-
Save ksnabb/271f4a7367b4f5571571c9a7a7ea6ecf to your computer and use it in GitHub Desktop.
Simple Javascript/HTML Counter
This file contains 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
function pubSub() { | |
const listeners = []; | |
return { | |
dispatch: (event) => listeners.forEach((l) => l(event)), | |
subscribe: (fun) => listeners.push(fun) | |
} | |
} |
This file contains 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
function state(initialValue, pubsub) { | |
let val = initialValue; | |
function setValue(newValue) { | |
val = newValue; | |
pubsub.dispatch(newValue); | |
} | |
function getValue() { | |
return val; | |
} | |
return { | |
getValue, | |
setValue | |
} | |
} |
This file contains 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
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