Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@XXimiCC

XXimiCC Feb 11, 2016

implementation observable pattern

Owner

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