Created
February 11, 2016 19:09
-
-
Save XXimiCC/fea65361da5e2d4f63b4 to your computer and use it in GitHub Desktop.
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(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); | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
implementation observable pattern