SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2005
    Posts
    30
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy THIS referencing problem

    Hi guys,

    I'm using a JS class to apply some event handling functions to a table.

    I have a referencing problem though.

    I'm posting simplified code here which contains everything that's connected with the problem and which is easier to read then the whole script:


    function thisIsAClass()
    {
    // This method is called for the "onClick" event.
    this.handleOnClick = function(event)
    {
    // if event (mozilla) doesn't exist (as in IE) replace it with the MS equivalent window.event
    if(event == null){event = window.event;}

    this.selectRow(this);
    }
    }

    The problem part is "this.selectRow(this);". As you can see the first "this" is meant to refer to the class itsself...but the thing is that of course as this is a handler function "this" actually refers to the target which was affected by the event onClick so there is the problem.

    Is there a way to call a class method without "this"? I need variables that exist only within the class so calling an 'external' function is not possible. Or is it?

    I tried lots of approaches but neither of them worked, so now I'm asking you for help

    Cheers, Florian

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function thisIsAClass()
    {
    	// This method is called for the "onClick" event.
    	var me = this;
    	this.handleOnClick = function(event)
    	{
    	// if event (mozilla) doesn't exist (as in IE) replace it with the MS equivalent window.event
    		if(event == null){event = window.event;}
    
    		me.selectRow(me);
    	}
    }

  3. #3
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Read this article, specifically the bit at the bottom about using .bind.

  4. #4
    SitePoint Enthusiast
    Join Date
    Sep 2005
    Posts
    30
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey guys, thanks for your very helpful replies. What "jimfraser" posted was what I had tried before - and it wouldn't work. Well, now it does

    Thanks Buddy Bradley for providing the excellent article about this issue. I had this problem with AJAX before so this is really helping me

    Cheers, Florian


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
  •