﻿/**
* @author 		Matthew Foster
* @date		June 6th 2007
* @purpose		To have a base class to extend subclasses from to inherit event dispatching functionality.
* @procedure	Use a hash of event "types" that will contain an array of functions to execute.  The logic is if any function explicitally returns false the chain will halt execution.
*/
var EventDispatcher = function() { };

//EventDispatcher.prototype.listenerChain = {};

EventDispatcher.prototype.buildListenerChain = function() {
    if (!this.listenerChain)
        this.listenerChain = {};
}

EventDispatcher.prototype.addEventListener = function(type, listener) {
    if (!listener instanceof Function)
        throw { message: "Listener isn't a function" };
    this.buildListenerChain();

    if (!this.listenerChain[type])
        this.listenerChain[type] = [listener];
    else
        this.listenerChain[type].push(listener);
}

EventDispatcher.prototype.hasEventListener = function(type) {
    this.buildListenerChain();
    return (typeof this.listenerChain[type] != "undefined");
}

EventDispatcher.prototype.removeEventListener = function(type, listener) {
    this.buildListenerChain();
    if (!this.hasEventListener(type))
        return false;

    for (var i = 0; i < this.listenerChain[type].length; i++)
        if (this.listenerChain[type][i] == listener)
            this.listenerChain.splice(i, 1);
}

EventDispatcher.prototype.dispatchEvent = function(type, args) {
    this.buildListenerChain();

    if (!this.hasEventListener(type))
        return false;

    for (var i = 0; i < this.listenerChain[type].length; i++) {
        this.listenerChain[type][i].apply(this,[type,args]);
    }
}
