- Messages
- 1,420
- Reaction score
- 46
- Points
- 48
The project I am currently working on in Javascript is based around a Google Maps object. This map has multiple event handlers associated with it and I am having problems understanding how to maintain the variable scope when the handler event is called.
Currently, I am using an assigned variable called 'calledObject', but this is both messy and I know it is not the proper way of doing it.
I have truncated the code for simplicity to the main items:
What I want this to do is maintain the link to the 'this' so that I can call this.addVertex rather then calledObject.addVertex like this:
Obviously, this does not work as when the click event is called the 'this' has changed from referencing the instance of FC().
Basically, I am unsure as to how to form the closure on the variables within the FC object, so that when the click event is called the 'this' object is pointing to the correct thing. I have been reading multiple tutorials and seem to be getting nowhere.
Any assistance would be greatly appreciated.
Currently, I am using an assigned variable called 'calledObject', but this is both messy and I know it is not the proper way of doing it.
I have truncated the code for simplicity to the main items:
Code:
[B]var calledObject = null;[/B]
function FC(){
[B]calledObject = this;[/B]
this.initialiseMap = function(){
//Create map code truncated here
google.maps.event.addListener(map, 'click', function(event){
[B]calledObject[/B].addVertex(event.latLng.lat(), event.latLng.lng(), 0, false, false);
//This works but doesn't seem like the right way of doing it
});
this.addVertex = function(){
//Add vertex
}
}
Code:
function FC(){
this.initialiseMap = function(){
//Create map code truncated here
google.maps.event.addListener(map, 'click', function(event){
[B]this[/B].addVertex(event.latLng.lat(), event.latLng.lng(), 0, false, false);
//This does not work, closure is not formed
});
this.addVertex = function(){
//Add vertex
}
}
Basically, I am unsure as to how to form the closure on the variables within the FC object, so that when the click event is called the 'this' object is pointing to the correct thing. I have been reading multiple tutorials and seem to be getting nowhere.
Any assistance would be greatly appreciated.