Skip to content

Instantly share code, notes, and snippets.

@glava
Created January 17, 2014 15:49
Show Gist options
  • Save glava/8475660 to your computer and use it in GitHub Desktop.
Save glava/8475660 to your computer and use it in GitHub Desktop.
Custom events in JavaScript Mostly based on this excellent article http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
function EventTarget() {
this._listeners = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addListener: function(type, listener){
if (typeof this._listeners[type] == "undefined"){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
fire: function(event){
if (typeof event == "string"){
event = { type: event };
}
if (!event.target){
event.target = this;
}
if (!event.type){ //falsy
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type] instanceof Array){
var listeners = this._listeners[event.type];
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
},
removeListener: function(type, listener){
if (this._listeners[type] instanceof Array){
var listeners = this._listeners[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
}
};
var MyObject = function() {
EventTarget.call(this);
this.call = function() {
this.foo();
}
}
MyObject.prototype = new EventTarget();
MyObject.prototype.constructor = MyObject;
MyObject.prototype.foo = function() {
this.fire("foo");
};
var o = new MyObject();
o.addListener("foo", function(){
alert("Foo just happened.");
});
o.call();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment