Created
August 26, 2016 13:46
-
-
Save maxidr/2bfd14aae168e2ad03f4af3b5a85f158 to your computer and use it in GitHub Desktop.
Add change listener on mitrhil prop
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 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of use: