Javascript class problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • theS70RM
    New Member
    • Jul 2007
    • 107

    Javascript class problem

    Hey,

    This is probably just a question of syntax but i cant figure it out!

    i have a javascript class with several functions, one being something like ...


    Code:
    TreeView.prototype.showItems = function(id) {
    
    	itemImg = document.createElement("img");
    	itemImg.src = "images/treeplus.gif";
    	itemImg.onclick = function(){this.otherfunction();
            document.appendChild(itemImg);
    }
    
    TreeView.prototype.otherfunction = function(id) {
             //do something
    }
    In the following line:
    Code:
    itemImg.onclick = function(){this.otherfunction();
    How do i make the otherfunction() part reference the current class, obviously this. doesnt work as the element is appended somewhere within the html doc and the onclick even looks for some global function called otherfunction, not within the TreeView class.

    any ideas? (or a work around)

    Ta

    Andy
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    the simplest way to fix the scope would be:

    [CODE=javascript]var me = this;

    itemImg.onclick = function() { me.otherfunctio n() };[/CODE]
    kind regards

    Comment

    • theS70RM
      New Member
      • Jul 2007
      • 107

      #3
      dude i love u!

      solved so many of my probs cheers.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        no problem ;) ... post back to the forum anytime you have more questions ...

        kind regards

        Comment

        Working...