Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent duplicate event handlers against same element

Status
Not open for further replies.

ranadhir

Programmer
Nov 4, 2003
54
0
0
IN
posted Today 5:43 PM
--------------------------------------------------------------------------------
We are attachign to a new window to listen to events on that window:

winHandle=window.open("....jsp");
if( window.attachEvent ) {
winHandle.document.attachEvent('onclick',detectType);
winHandle.document.attachEvent('onkeyup',detectType);}
In the detectType function, we attach and eventhandle to the individual element,based on the element type

function detectType (e)
{
var targ;
if (!e) var e=winHandle.event;
if (e.target){targ=e.target;}
else if(e.srcElement){targ=e.srcElement;}
if (targ.nodeType==3){targ=targ.parentNode;}

var tagName=targ.tagName;

switch(tagName)
{
......
case "INPUT":
targ.attachEvent("ondeactivate",capturecontent);
break;
default:
targ.attachEvent("onblur",capturecontent);
break;

}
...
}

Now in some cases,both the mouse and kep events would fire and cause the event handler to be attached twice.
Is ther some way to detect if an event handler has already been attached,to avoid re-attaching it?
 
But don't you want it to attach twice? Do you mean you don't want the event handler to fire twice?

You can add some code that prevents the code from executing twice within 10 milliseconds. Something like...
Code:
var IsDetecting = false;

function detectType(e){
  if(IsDetecting) return;

  try
  {
    IsDetecting = true;

    // detectType function body goes here.

  }
  finally
  {
    setTimeout('IsDetecting=false',10);
  }
}

Adam
 
I read through your post again and I might have misunderstood your question. If you want to prevent detectType from firing from both the onclick and onkeyup event of the document, use the code above.

But if what you want is to keep the detectType function from attaching to the INPUT events more than once, I think the easiest thing to do would be to call the detachEvent right before you call the attachEvent method. Then you can be sure there is only one instance of the capturecontent function assigned as the event handler.

Personally, I think I would combine the two solutions for extra protection.

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top