Connecting Tech Pros Worldwide Forums | Help | Site Map

Work Around for IE javascript "this"

Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#1: Jul 1 '09
I am having trouble with my script in IE(IE6) and how it treats a "this". I am thinking it might have something to do with my event wrapper function(see code) but would like to keep that wrapper.

Expand|Select|Wrap|Line Numbers
  1. function BuildIt()
  2. {
  3.     var taA=document.getElementById("taArea");
  4.     var soA=document.getElementById("soArea");
  5.     if((taA!=undefined)&&(soA!=undefined))
  6.     {
  7.         for(var i=0;i<NumberOfBoxes;i++)
  8.         {
  9.             var taObj = document.createElement('textarea');
  10.             with(taObj) 
  11.             {
  12.                 cols="24";
  13.                 rows="6";
  14.                 id="ta"+i.toString();
  15.             }
  16.             taA.appendChild(taObj);
  17.             AddEventWrapper(taObj,"change",function(evt){ReCalc(this);});
  18.     }
  19. }
  20.  
  21. function AddEventWrapper(myElement,evtName,evtAction)
  22. {
  23.     if(document.addEventListener) 
  24.     {
  25.       myElement.addEventListener(evtName, evtAction,false);
  26.   } 
  27.   else if(document.attachEvent) 
  28.   {//prepend the "on" to the event
  29.       myElement.attachEvent("on"+evtName,eval(evtAction));
  30.   } 
  31. }
  32.  
  33. function ReCalc(o)
  34. {
  35.  
  36.     if(o!=undefined)
  37.     {
  38.         alert(o==document);
  39.     }
  40. }
  41.  
  42.  
Now, in FF, everything is fine, ReCalc gets passed the correct instance of a textarea, in IE however it's always the document object itself.

I have tried many combinations for the line:
AddEventWrapper(taObj,"change",function(evt){ReCal c(this);});
Such as sending in the taObj, the id string for the current taObj, using eval in various places etc. All of those met with the same result, no matter which textarea i wrote in, it was always the last one that thought it was doing something.

Is there anyway to get the correct object to be passed into the event handler function in both IE and FF?

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,652
#2: Jul 1 '09

re: Work Around for IE javascript "this"


you could also try the addEvent() functions for AddEventWrapper(). they are well tested and should work.

see the links at the end of this post
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#3: Jul 1 '09

re: Work Around for IE javascript "this"


Ah many thanks, I went with this one: http://www.dustindiaz.com/rock-solid-addevent/ and it seemed to do the trick.
Reply