Skip to content

Instantly share code, notes, and snippets.

@maxidr
Created August 26, 2016 13:46
Show Gist options
  • Save maxidr/2bfd14aae168e2ad03f4af3b5a85f158 to your computer and use it in GitHub Desktop.
Save maxidr/2bfd14aae168e2ad03f4af3b5a85f158 to your computer and use it in GitHub Desktop.
Add change listener on mitrhil prop
const m = require('mithril')
function emitChangeToSubscribers(subscribers, newState, oldState){
subscribers.forEach(function(subscriber){
subscriber.call(null, newState, oldState)
})
}
module.exports = function(initState){
const store = m.prop(initState)
const subscribers = []
function prop(){
if( arguments.length > 0 ) {
// arguments[0] -> newState
// store() -> oldState
emitChangeToSubscribers(subscribers, arguments[0], store())
}
return store.apply(null, arguments)
}
prop.onChange = function(callbackFn){ subscribers.push(callbackFn) }
return prop
}
@maxidr
Copy link
Author

maxidr commented Aug 26, 2016

Example of use:

const name = prop('John')

name.onChange(function(newValue, previousValue){ 
  console.log('The name change from ' + previousValue + ' to ' + newValue)
})

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