From: matt.snider on
On Jan 29, 9:23 am, john_woo <john_...(a)canada.com> wrote:
> Hi,
>
> I need to implement API by which all onclick envets in same document
> can be in flexible control (disable/enable on demand).
>
> I tried the followings:
>
> 1. overwrite onclick function:
>         if (window.captureEvents){
>                 window.captureEvents(Event.CLICK);
>                 window.onclick=myfunction;
>         }
>         else{
>                 document.captureEvents(Event.CLICK);
>                 document.onclick=myfunction;
>         }
>
>       document.addEventListener("click", myfunction, true); //or
>       document.attachEvent("click", myfunction);
>
> 2. then in myfunction:
>       if (event.stopPropagation) event.stopPropagation();
>       else event.cancelBubble = true;    //or
>       if (event.preventDefault) event.preventDefault();
>       else event.returnValue = false;
>
> However, the above can only overwrite default behavior, can't be
> applied to those buttons which are associated with specific functions/
> handlers;
>
> Then traversing through document tree to find out and overwrite those
> functions. This leads to big problem - when enabling onclick events,
> those specific handling functions gone!
>
> I'm wondering, what is the right way to design/implement such API?
>
> Thanks,
> --
> John

I'm not sure if you found a solution, but there are ways to do this.
If you use a framework like YUI to attach all your events, the
framework will keep a collection of all events, which you can fetch
and then turn them each off. Alternatively, you could do something
simpler by wrapping your event handlers in another function that knows
to check for a specific toggle parameters:

var activateClickHandlers = true;

var myClickHandlerWrapper = function(fx) {
return function() {
if (activateClickHanlders) {
fx.apply(this, arguments);
}
else {
return false;
}
};
};

and when you attach a click event, you would use:

myelement.onclick = myClickHandlerWrapper(function(e) {
// your function
});

now if you set 'activateClickHandlers' to false, then the wrapper
function will return false to all your onclick handlers. Otherwise,
the callbacks will behave normally.

-matt