Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* make listener infrastructure */
function makeStateHolder() {
let state = undefined;
const listeners = [];
return {
addListener(newListener) {
listeners.push(newListener);
},
getState() {
return state;
},
updateState(newState) {
state = newState;
listeners.forEach(listener => listener.stateChanged(newState));
},
};
}
const stateHolder = makeStateHolder();
/* bank account logic */
function makeBankAccount(balance) {
stateHolder.updateState(balance);
return {
withdraw(amount) {
balance -= amount;
stateHolder.updateState(balance);
},
deposit(amount) {
balance += amount;
stateHolder.updateState(balance);
},
getBalance() {
return balance;
},
};
}
const bankAccount = makeBankAccount(4000);
/* make listeners */
const financeListener = {
stateChanged(state) {
if (state < 4000) {
bankAccount.deposit(1000);
}
},
};
const webpageListener = {
stateChanged(state) {
console.log('DISPLAYED BALANCE', state);
},
};
stateHolder.addListener(financeListener);
stateHolder.addListener(webpageListener);
/* withdraw 100 */
bankAccount.withdraw(100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.