Skip to content

Instantly share code, notes, and snippets.

@XXimiCC
Created February 11, 2016 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XXimiCC/fea65361da5e2d4f63b4 to your computer and use it in GitHub Desktop.
Save XXimiCC/fea65361da5e2d4f63b4 to your computer and use it in GitHub Desktop.
function observable(obj) {
obj._events = [];
obj.on = function (eventName, fn) {
this._events[eventName] = (this._events[eventName]) ? this._events[eventName] : [];
this._events[eventName].push({
fn: fn,
once: false
});
}
obj.one = function (eventName, fn) {
this._events[eventName] = (this._events[eventName]) ? this._events[eventName] : [];
this._events[eventName].push({
fn: fn,
once: true
});
}
obj.fire = function (eventName) {
var args = Array.prototype.slice.call(arguments).slice(1);
this._events[eventName] = (this._events[eventName]) ? this._events[eventName] : [];
this._events[eventName].forEach(function (listener, index, array) {
listener.fn.apply(null, args);
if (listener.once) {
array.splice(index,1);
}
});
}
obj.unbind = function (eventName, fn) {
if (!fn) {
this._events[eventName] = [];
} else {
this._events[eventName].forEach(function (listener, index, array) {
if (fn === listener.fn) {
array.splice(index,1);
}
});
}
}
}
@XXimiCC
Copy link
Author

XXimiCC commented Feb 11, 2016

implementation observable pattern

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