Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rokujyouhitoma/17fa8370362fc7a37c7c2cce0de5a98f to your computer and use it in GitHub Desktop.
Save rokujyouhitoma/17fa8370362fc7a37c7c2cce0de5a98f to your computer and use it in GitHub Desktop.
Event, EventTarget, EventListener
var Event = function(type, target, sender, payload){
this.type = type;
this.target = target;
this.sender = sender;
this.payload = payload;
};
var EventTarget = function(){
this.eventListeners = [];
};
EventTarget.prototype.listen = function(type, listener){
var self = this;
var wrapper = function(e) {
if (typeof listener.handleEvent != 'undefined') {
listener.handleEvent(e);
} else {
listener.call(self, e);
}
};
console.log(this);
this.eventListeners.push({
object: this,
type: type,
listener: listener,
wrapper: wrapper
});
};
EventTarget.prototype.unlisten = function(type, listener){
var eventListeners = this.eventListeners;
var counter = 0;
while(counter < eventListeners.length){
var eventListener = eventListeners[counter];
if (eventListener.object == this &&
eventListener.type == type &&
eventListener.listener == listener){
eventListeners.splice(counter, 1);
break;
}
++counter;
}
};
EventTarget.prototype.dispatch = function(type, sender, payload){
var eventListeners = this.eventListeners;
var counter = 0;
while(counter < eventListeners.length){
var eventListener = eventListeners[counter];
if (eventListener.object == this &&
eventListener.type == type){
if(type instanceof Event){
type.target = this;
type.sender = sender;
type.payload = payload;
eventListener.wrapper(type);
} else {
eventListener.wrapper(new Event(type, this, sender, payload));
}
}
++counter;
}
};
var EventListener = function(callback){
this.callback = callback;
};
EventListener.prototype.handleEvent = function(event){
this.callback(event);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment