0
  1. I have an object which creates a slideshow.
  2. I want to have several slideshows on a page
  3. I have an event handler for slideshow element inside it
  4. I want the event handler to know which slideshow object has created an item clicked

-

slideshow=function(){
 var g = document.createElement(...);
 ...
 g.onclick = f1;
 f1 = function(slideshow_instance, event) {
 //EXPLAIN ME HOW TO GET THE slideshow_instance
 }
}
var sl1 = new slideshow();
var sl2 = new slideshow();

Clicking on an element slideshow has created should return either

sl1

or

sl2

I explain well?

asked Jan 11, 2011 at 5:59
5
  • Where is the slideshow_instance exactly created? Commented Jan 11, 2011 at 6:15
  • Have a read of this: stackoverflow.com/questions/4584845/… Commented Jan 11, 2011 at 6:33
  • @Epeli the slideshow_instance is the same as this keyword... But I can't use it inside an event handler Commented Jan 11, 2011 at 6:55
  • see also stackoverflow.com/questions/337878/js-var-self-this Commented Jan 11, 2011 at 8:30
  • You should write slideshow variable with capital S so that we can know that it is the constructor. Commented Jan 11, 2011 at 16:58

2 Answers 2

5

Short answer, use: this.

Longer answer, what you want is:

slideshow=function(){
 /* ... */
 var self = this; 
 f1 = function(event) {
 // do stuff with self.
 }
}

The reason you need to point to this using self is that event handlers will change the meaning of this when they are called. But at the time the object is created this properly refer to the correct object (an instance of slideshow). The reason we can access the self variable during event callback is because it has been captured by a closure.

Feel free to google or search on stackoverflow any word/terminology from the above description if you need further explanation.

answered Jan 11, 2011 at 7:11
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for being a little cleaner and easier to read than mine :)
1
slideshow=function(){
 var g = document.createElement(...);
 g._objRef = this;
 ...
 g.onclick = f1;
 f1 = function(event) {
 alert(this._objRef);
 }
}
var sl1 = new slideshow();
var sl2 = new slideshow();

A bit of a hack imo, but it should do the trick.

answered Jan 11, 2011 at 7:09

2 Comments

you both are good! The solution was so simple but I couldn't see it!
You could just use closure here instead of referring it via dom element (which can be even slow).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.