[thelist] [JavaScript] Event question for you event experts

Matt Warden mwarden at gmail.com
Mon Feb 20 14:32:04 CST 2006


> Right, I didn't mean that it was bad, I just don't want to bust the code - I want to be able to
> attach/detach events reliably at any time, without worrying about breaking existing functionality.
>
> Thanks for both of those links, I should have thought about the Yahoo lib. I'll take a slog
> through both!

Yes, this is exactly what the code in my sandbox will allow you to do:

function addObjectEventListener(obj, event, funct)
{
    // Assign new anonymous function if we're passed a js string
    // instead of a function reference.
    if (typeof funct == 'string') {
        funct = new Function(funct);
    }

    if (obj.addEventListener) {
        obj.addEventListener(event, funct, false);
    } else if (obj.attachEvent) {
        obj.attachEvent('on'+event, funct);
    }
    else {
        eval('var old = obj.on'+event+';');
        if (old != null) {
            eval('obj.on'+event+' = function() {'
                +'old();'
                +'funct();'
            +'};');
        }
        else {
            eval('obj.on'+event+' = funct;');
        } // end if
    } // end if
} // end function addListener


function addBodyOnload(funct)
{
    addObjectEventListener(window, 'load', funct);
} // end function addBodyOnload


calling addBodyOnload(myFunctionName); or addBodyOnload("var code =
toExecute();"); will attach another function to the onload list queue
without affecting anything already queued up. It basically does this:

var old = window.onload;
window.onload = function() {
     old();
     new();
}

where new() is your new function to be added to the execution queue onload.

As you can see, you can call this as many times as you want at any
point you want and it doesn't matter what is already attached to
window.onload.

This is analogous to an increment:

function addOne()
{
    foo = foo + 1;
}

It doesn't matter what foo is when you call addOne().

Using this function may be simpler for you than trying to download and
set up the entire Yahoo library (although if you see uses for its
other functionaly, it's a great library and I would highly recommend
it).

--
Matt Warden
Miami University
Oxford, OH, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.



More information about the thelist mailing list