26/08/2011 Development / java script

Esse foi o patter que eu escolhi para o gerenciamento dos eventos dentro do HomeBroker da Xp Investimentos

/* Gerenciador de eventos */
/***************************************************************************/
var $Event = {};
(function(s){

    var events = {};

        /* Aciona um evento */
        s.handleEvent = function() {

            var evt = arguments[0];
            var handlers = events[evt];
            var handler;

            if (!handlers || handlers.length == 0) {
                return false;
            }

            var len = handlers ? handlers.length : 0;
            var args = [];
            var i = arguments.length - 1;

            for (var x = 0; x < i; x++) {
                args[x] = arguments[x + 1];
            }

            while (len--) {
                handler = handlers[len];
                handler.func.apply(handler.ctx, args);
            }
        };

        /* Adiciona um evento */
        s.addHandler = function(evt, func, ctx) {

            if (!events[evt]) {
                events[evt] = [];
            }

            events[evt].push({'func' : func, 'ctx' : ctx});
        };

        /* Remove um evento */
        s.removeHandler = function(evt, cb, ctx) {
           
            var handlers = events[evt];
            var handler;

            if (!handlers || handlers.length == 0) {
                return false;
            }

            var len = handlers.length;

            while(len--){
                handler = handlers[len];

                if(handler){
                    if (ctx) {
                        if (cb) {
                            if (handler.ctx == ctx && handler.func == cb) {
                                handlers.splice(len, 1);
                            }
                        } else {
                            handlers.splice(len, 1);
                        }
                    }else{
                        handlers.splice(len, 1);
                    }
                }
            }
        };
})($Event);