Last active
January 24, 2019 00:59
-
-
Save katelynsills/06edba8790da6c4454eb029922b80878 to your computer and use it in GitHub Desktop.
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
/* 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