Novemberborn, Straight lines circle sometime

Event Cache Follow-up

Finally, here’s a short follow-up to the original Event Cache article. Let’s start with the best news: the script is now known to work in Internet Explorer, Safari and Mozilla.

Implementing

Something which had to be read through the lines in the original article was how to actually implement the script. Therefore, a little tutorial.

First we take Scott Andrew LePera’s addEvent code. The addEvent function [1] is as follows:

function addEvent(obj, evType, fn, useCapture){
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    } else {
        return false;
    }
}

This doesn’t take care of IE/Mac and other legacy browsers, so you might want to use this method by Simon Willison to get around that.

Anyway, onwards with adding the event to the cache! Here’s the modified version of Scott Andrew’s code which does exactly that:

function addEvent(obj, evType, fn, useCapture){
    var result;
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, useCapture);
        result = true;
    } else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        result = r;
    } else {
        return false;
    }

    EventCache.add(obj, evType, fn, useCapture);
    return result;
}

We also need to register the onunload handler so we can flush the cache:

addEvent(window, "unload", EventCache.flush);

And that’s it!

Sam Schillace pointed out that the code above was wrong… the method would return before Event Cache kicked in. Big Oops! Thanks for pointing that out, Sam!

(Edited June 3, 2005).

Event Cache, but without the cache

Ramon Leon pointed out to me the other day that it’d be easier to add an unload event which removes the event handler for each event, instead of caching the event and setting an unload event to flush the cache.

Well, yeah, that approach sounds good to me. It doesn’t mean, however, that you’re no longer using a cache: the unload event still contains references to the characteristics of the original event, you just can’t access those references. It’s a minor difference though, I’d say choose which method suits your needs best.

Footnotes

[1]: The original code has an alert to warn you that the event wasn’t set. I figured it’d be more useful if the function would simply return false, so it wouldn’t scare off visitors :)

link | javascript | 3 June 2005, 20:27



Novemberborn: Extra

About the author

Mark Wubben is a hacker/writer in Enschede, the Netherlands.

Read more about Mark...

Go to

Jobs (NL)

Xopus zoekt programmeurs! Verbeter de code en win!

Subscribe