- I have an object which creates a slideshow.
- I want to have several slideshows on a page
- I have an event handler for slideshow element inside it
- 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?
-
Where is the slideshow_instance exactly created?esamatti– esamatti2011年01月11日 06:15:40 +00:00Commented Jan 11, 2011 at 6:15
-
Have a read of this: stackoverflow.com/questions/4584845/…mplungjan– mplungjan2011年01月11日 06:33:28 +00:00Commented 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 handlerDan– Dan2011年01月11日 06:55:30 +00:00Commented Jan 11, 2011 at 6:55
-
see also stackoverflow.com/questions/337878/js-var-self-thisDan– Dan2011年01月11日 08:30:56 +00:00Commented Jan 11, 2011 at 8:30
-
You should write slideshow variable with capital S so that we can know that it is the constructor.esamatti– esamatti2011年01月11日 16:58:52 +00:00Commented Jan 11, 2011 at 16:58
2 Answers 2
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.
1 Comment
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.