Skip to content

Instantly share code, notes, and snippets.

@xphere
Created December 11, 2012 16:35
Show Gist options
  • Save xphere/4260118 to your computer and use it in GitHub Desktop.
Save xphere/4260118 to your computer and use it in GitHub Desktop.
EventDispatcher JS
EventDispatcher.prototype.addExtension = function() {
for (var i = 0; i < arguments.length; ++i) {
arguments[i].applyTo(this);
}
};
function Event() {
}
extend(Event.prototype, {
propagationStopped: false,
stopPropagation: function() {
this.propagationStopped = true;
return this;
},
isPropagationStopped: function() {
return this.propagationStopped;
}
});
function EventDispatcher() {
}
extend(EventDispatcher.prototype, {
listeners: {},
dispatch: function(eventName, event) {
var i, events;
event || (event = new Event);
events = this.getListeners(eventName);
for (i = 0; i < events.length; ++i) {
events[i].call(this, event);
if (event.isPropagationStopped && event.isPropagationStopped()) {
break;
}
}
return event;
},
on: function(eventName, priority, listener) {
if (listener === undefined) {
listener = priority;
priority = Event.PRIORITY_NORMAL;
}
this.listeners[eventName] || (this.listeners[eventName] = {});
this.listeners[eventName][priority] || (this.listeners[eventName][priority] = []);
this.listeners[eventName][priority].push(listener);
return {
remove: this.remove.bind(this, eventName, listener)
};
},
once: function(eventName, priority, listener) {
var once;
if (listener === undefined) {
listener = priority;
priority = Event.PRIORITY_NORMAL;
}
once = this.on(eventName, priority, function callback() {
once.remove();
listener.apply(listener, arguments);
});
return once;
},
remove: function(eventName, listener) {
for (var priority in this.listeners[eventName]) {
var events = this.listeners[eventName], position;
while ((position = events[priority].indexOf(listener)) > -1) {
delete events[priority][position];
}
if (events[priority].length === 0) {
delete events[priority];
}
}
return this;
},
removeAll: function(eventName) {
delete this.listeners[eventName];
return this;
},
hasListeners: function(eventName) {
return this.listeners[eventName] ? true : false;
},
getListeners: function(eventName) {
var result = [], collection = this.listeners;
if (eventName) {
collection = {};
collection[eventName] = this.listeners[eventName];
}
for (var name in collection) {
for (var priority in collection[name]) {
result = result.concat(collection[name][priority]);
}
}
return result;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment