Last active
October 5, 2017 21:24
-
-
Save nightspirit/b4731e058f16cfac2de4 to your computer and use it in GitHub Desktop.
Observable
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 Observable(init_value) { | |
var _value = init_value; | |
var subscriber = []; | |
function obs() { | |
if (arguments.length) { | |
_value = arguments[0]; | |
obs.trigger(); | |
return this; | |
} else { | |
return _value; | |
} | |
} | |
obs.on = function (fn) { | |
subscriber.push(fn); | |
return this; | |
}; | |
obs.off = function (fn) { | |
subscriber.forEach(function (f, i) { | |
if (fn === f) subscriber.splice(i, 1); | |
}) | |
}; | |
obs.trigger = function () { | |
subscriber.map(function (fn) { | |
fn(_value); | |
}); | |
} | |
return obs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment