Last active
March 16, 2017 01:38
-
-
Save Axighi/3b4b4c8cf255bc91d084839fbe3d51da 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
var CustomObject = function () { | |
var _this = this; | |
_this.events = {}; | |
_this.addEventListener = function(name, handler) { | |
if (_this.events.hasOwnProperty(name)) | |
_this.events[name].push(handler); | |
else | |
_this.events[name] = [handler]; | |
}; | |
_this.removeEventListener = function(name, handler) { | |
/* This is a bit tricky, because how would you identify functions? | |
This simple solution should work if you pass THE SAME handler. */ | |
if (!_this.events.hasOwnProperty(name)) | |
return; | |
var index = _this.events[name].indexOf(handler); | |
if (index != -1) | |
_this.events[name].splice(index, 1); | |
}; | |
_this.fireEvent = function(name, args) { | |
if (!_this.events.hasOwnProperty(name)) | |
return; | |
if (!args || !args.length) | |
args = []; | |
var evs = _this.events[name], l = evs.length; | |
for (var i = 0; i < l; i++) { | |
evs[i].apply(null, args); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment