0

I have an issue to access at some variables outside an anonymous function called in another function as parameter. This is the code :

clicked(){
    var lat;
    var lng;
    this.map.on('click',function(e) {
            var coordonneesDiv = document.getElementById("coordonnees");
            lat = e.latlng.lat;
            lng = e.latlng.lng;
            //var zoom = 18; 
            coordonneesDiv.innerHTML = "lat : " + lat + "<br/>" + "long : "+ lng;
            //Zoom lors d'un  click 
            //
            //this.map.setView([lat, lng], zoom);
    });
    this.getData(lat,lng); 
}

Is it possible to modify the lat and lng variables inside the anonymous function to use them after (in getData).

Thanks for you answers

-------- Correction -----

clicked(){
    var lat;
    var lng;
    var self = this;
    console.log(self);
    this.map.on('click',function(e,self){
            console.log(self);
            var coordonneesDiv = document.getElementById("coordonnees");
            lat = e.latlng.lat;
            lng = e.latlng.lng;
            //var zoom = 18; 
            coordonneesDiv.innerHTML = "lat : " + lat + "<br/>" + "long : "+ lng;
            //Zoom lors d'un  click 
            self.getData(lat,lng);
            //this.map.setView([lat, lng], zoom);
    });
    this.getData(lat,lng); 
}

Am I doing it wrong ?

The first log send me that the self exist. But the second not.

Sorry for my clumsiness...

  • No it is not possible as you have it now. Move the call to `getData` inside the anonymous function. – Dark Falcon Jan 20 '16 at 16:02
  • Thanks for your reply. The problem is the function getData is not callable within the anonymous function. The function is not in the scope. I got this error when i do it : EXCEPTION: TypeError: this.getData is not a function. – Maxime Brassart Jan 20 '16 at 16:21
  • `this` is a keyword which refers to the `this` in the current scope. Because you're in an anonymous function, the current scope is different. Do a `var self = this;` and use `self` instead of `this`. – Dark Falcon Jan 20 '16 at 16:25
  • I reedited the post. Sorry to bother you... – Maxime Brassart Jan 20 '16 at 16:40
  • Yes. Do not pass `self` into the function. The `self` you added as a function parameter hides the outer `self`. (Why would you think you needed to add it as a parameter?) The anonymous function is a closure, which means it captures a reference to variables in the containing scope, including `self`. – Dark Falcon Jan 20 '16 at 16:42
  • It's work ! Thanks a lot. I dont know why I added `self` in parameter. I thought `self` will be not in the scope of the anonymous function. Your explanation is clear. I understand now. Thanks again ! – Maxime Brassart Jan 20 '16 at 16:54

0 Answers0