Skip to content

Instantly share code, notes, and snippets.

@nightspirit
Last active October 5, 2017 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nightspirit/b4731e058f16cfac2de4 to your computer and use it in GitHub Desktop.
Save nightspirit/b4731e058f16cfac2de4 to your computer and use it in GitHub Desktop.
Observable
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