Reputation: 62714
Assuming I have the following:
function test() {
this.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(this.message); // Incorrect as "this" refers to this.mypolygon
});
}
How do I make it such that I can correctly have "Hello World" be alerted within the event listener? In other words, get the correct context of "this from within the eventlistener?
Upvotes: 0
Views: 47
Reputation: 8640
Don't use the this
keyword. Use something else that doesn't get changed inside the addListener
:
function test() {
foo.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(foo.message);
});
}
or even cleaner:
function test() {
var message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(message);
});
}
alternatively, you could do:
function test() {
this.message = "Hello World";
this.marker = //A google marker object
var self = this;
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(self.message);
});
}
Lastly, if you really want to use this
inside the click handler, you can use bind
:
function test() {
this.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', myFunc.bind(this) );
function myFunc(mouseEvent) {
alert(this.message);
}
}
Upvotes: 0
Reputation: 10407
You will need a closure.
function test() {
var self = this;
this.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(self.message); // Now "self" points to parent function scope
});
}
Upvotes: 1