Work Around for IE javascript "this"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    Work Around for IE javascript "this"

    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.

    [code=javascript]
    function BuildIt()
    {
    var taA=document.ge tElementById("t aArea");
    var soA=document.ge tElementById("s oArea");
    if((taA!=undefi ned)&&(soA!=und efined))
    {
    for(var i=0;i<NumberOfB oxes;i++)
    {
    var taObj = document.create Element('textar ea');
    with(taObj)
    {
    cols="24";
    rows="6";
    id="ta"+i.toStr ing();
    }
    taA.appendChild (taObj);
    AddEventWrapper (taObj,"change" ,function(evt){ ReCalc(this);}) ;
    }
    }

    function AddEventWrapper (myElement,evtN ame,evtAction)
    {
    if(document.add EventListener)
    {
    myElement.addEv entListener(evt Name, evtAction,false );
    }
    else if(document.att achEvent)
    {//prepend the "on" to the event
    myElement.attac hEvent("on"+evt Name,eval(evtAc tion));
    }
    }

    function ReCalc(o)
    {

    if(o!=undefined )
    {
    alert(o==docume nt);
    }
    }

    [/code]

    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){ ReCalc(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
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    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

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

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

      Comment

      Working...