Created
April 22, 2013 17:02
-
-
Save julsfelic/5436730 to your computer and use it in GitHub Desktop.
The Observer Pattern
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 EventTarget() { | |
this.handlers = {}; | |
} | |
EventTarge.prototype = { | |
constructor: EventTarget, | |
addHandler: function(type, handler) { | |
if (typeof this.handlers[type] == "undefined") { | |
this.handlers[type] = []; | |
} | |
this.handlers[type].push(handler); | |
}, | |
fire: function(event) { | |
if (!event.target) { | |
event.target = this; | |
} | |
if (this.handlers[event.type] instanceof Array) { | |
var handlers = this.handlers[event.type]; | |
for (var i = 0, len = handlers.length; i < len; i++) { | |
handlers[i](event); | |
} | |
} | |
}, | |
removeHandler: function(type, handler) { | |
if (this.handlers[type] instanceof Array) { | |
var handlers = this.handlers[type]; | |
for (var i = 0, len = handlers.length; i < len; i++) { | |
if (handlers[i] === handler) { | |
break; | |
} | |
} | |
handlers.splice(i, 1); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment