469,275 Members | 1,443 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,275 developers. It's quick & easy.

Javascript class problem

107 100+
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 ...


Expand|Select|Wrap|Line Numbers
  1. TreeView.prototype.showItems = function(id) {
  2.  
  3.     itemImg = document.createElement("img");
  4.     itemImg.src = "images/treeplus.gif";
  5.     itemImg.onclick = function(){this.otherfunction();
  6.         document.appendChild(itemImg);
  7. }
  8.  
  9. TreeView.prototype.otherfunction = function(id) {
  10.          //do something
  11. }
In the following line:
Expand|Select|Wrap|Line Numbers
  1. 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
Feb 20 '08 #1
3 954
gits
5,390 Expert Mod 4TB
hi ...

the simplest way to fix the scope would be:

Expand|Select|Wrap|Line Numbers
  1. var me = this;
  2.  
  3. itemImg.onclick = function() { me.otherfunction() };
kind regards
Feb 21 '08 #2
theS70RM
107 100+
dude i love u!

solved so many of my probs cheers.
Feb 25 '08 #3
gits
5,390 Expert Mod 4TB
no problem ;) ... post back to the forum anytime you have more questions ...

kind regards
Feb 25 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by Alex Fitzpatrick | last post: by
2 posts views Thread by Jackson Yap | last post: by
7 posts views Thread by Kevin Newman | last post: by
11 posts views Thread by trinitypete | last post: by
8 posts views Thread by chrisdude911 | last post: by
8 posts views Thread by rn5a | last post: by
2 posts views Thread by sorobor | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.