Over a million developers have joined DZone.

Javascript Window Event Handling Manager

·
I've seen a lot of window.onload managers, so I generalized it for any window event handler. This assumes prototype.

// BurntoEventManager
// http://brentfitzgerald.com/
// January 2007

var BurntoEventManager = {
    handlers: {},
    add: function(handler_name, method) {
        if(this.handlers[handler_name] == null) {
            this.handlers[handler_name] = new Array();
        }
        this.handlers[handler_name].push(method);
        
        // Now update the window event handler
        window[handler_name] = function(evt) {
            this.handlers[handler_name].each(function(m) {
                m(evt);
            }.bind(this));
        }.bind(this);
    },
    
    clear: function(handler_name) {
        this.handlers[handler_name] = null;
        window[handler_name] = function() {};
    },
    
    get: function(handler_name) {
        return this.handlers[handler_name];
    }
}

For example, consider if later on in our application we want to add an onclick handler.

BurntoEventManager.add("onclick", function(evt) { alert(evt) });
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}