talideon.com

Blackout Ireland

April 8, 2005 at 4:55PM I have some really strange old code.

I found this sitting amongst some old JavaScript libraries of mine:

function _DefaultHandler() {
    return true;
}

function AttachEventHandler(obj, evtName, fn) {
    var oldHandler = obj["on" + evtName] || _DefaultHandler;
    obj["on" + evtName] = function(evt) {
        evt = evt || window.event;
        return oldHandler(evt) && fn(evt);
    }
}

A few thoughts:

  1. This is rather clever! Obviously I wrote this under the influence of alcohol. [wink]
  2. Was I doped up on Perl when I wrote this?
  3. When did attachEvent() and addEventListener() become mainstream? And why didn’t I use them?
  4. A bit closure-happy, isn’t it?

In case anybody’s wondering, this code isn’t quite what I first found: the original code used eval() to get the originally assigned handler and again to assign the new one. Urgh!