SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Preserving 'this' keyword (attachEvent / MSIE)

    Has anyone come across a "simple" (not much code) solution to preserving the 'this' keyword in MSIE6 (hopefully without resorting to just 'onclick=func' since I might want to use multiple functions on the same event handler).

    I've seen one or two solutions, but the code volume is pretty high, in addition to the complexity.
    Last edited by SoulScratch; Feb 16, 2008 at 17:01.

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SoulScratch View Post
    Has anyone come across a "simple" (not much code) solution to preserving this 'this' keyword in MSIE6 (hopefully without resorting to just 'onclick=func' since I might want to use multiple functions on the same event handler).

    I've seen one or two solutions, but the code volume is pretty high, in addition to the complexity.
    I use this function (which I did not write) for appending non-removable code to event handlers. It has never failed.

    obj is the reference to the object.
    evt is a string specifying the event (must start with 'on').
    func is the function to append.

    Code:
    function addToHandler(obj, evt, func)
     {
      if(obj[evt])
       {
        obj[evt]=function(f,g)
        {
         return function()
         {
          f.apply(this,arguments);
          return g.apply(this,arguments);
         };
        }(func, obj[evt]);
       }
       else
        obj[evt]=func;
     }
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Evangelist
    Join Date
    Jan 2005
    Posts
    502
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can take a look at Dean Edwards' solution


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •