Created
May 6, 2013 16:32
-
-
Save jarek-foksa/5526247 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| Object.prototype.listen = (eventName, callback) -> | |
| if @addEventListener | |
| @addEventListener eventName, callback | |
| else | |
| if @hasOwnProperty('__events__') == false | |
| setDescriptor @, '__events__', | |
| value: {} | |
| enumerable: false | |
| if @__events__[eventName] == undefined | |
| @__events__[eventName] = {} | |
| setDescriptor @__events__[eventName], 'counter', | |
| value: 0 | |
| enumerable: false | |
| @__events__[eventName].counter += 1 | |
| @__events__[eventName][@__events__[eventName].counter] = callback | |
| Object.prototype.unlisten = (eventName, callback) -> | |
| if @removeEventListener | |
| @removeEventListener eventName, callback | |
| else | |
| if @hasOwnProperty('__events__') == false | |
| return | |
| callbacks = @__events__[eventName] | |
| if callbacks == undefined | |
| return | |
| for key, _callback of callbacks | |
| if _callback == callback | |
| delete callbacks[key] | |
| Object.prototype.trigger = (eventName, args...) -> | |
| if @hasOwnProperty('__events__') == false | |
| return | |
| callbacks = @__events__[eventName] | |
| if callbacks == undefined | |
| return | |
| # If there is an error in any of the callbacks then it will be thrown only after all | |
| # callbacks were fired, this is necesarry to prevent error in one callback from stopping | |
| # all subsequent callbacks | |
| catchedError = null | |
| for key, callback of callbacks | |
| try | |
| callback.apply global, args | |
| catch error | |
| if catchedError == null | |
| catchedError = error | |
| if catchedError | |
| throw catchedError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment