0
votes

Once I capture the click event on a leaflet marker and go to the associated function, I loose this for current context.

Marker create code:

const marker = L.marker([lon, lat], c).addEventListener("click", this.onClickRainFall).addTo(map);

and associated function is:

private onClickRainFall(e){
var sourceUrl2 = "a.b.c.d/" + e.sourceTarget.options.properties.abc;
this.getData(sourceUrl2);

}

Here when I try to access this.getData, at runtime I get error that "ERROR TypeError: this.getData is not a function"

Function definition for getData is:

public getData(sourceUrl){
console.log('I  am called');
this.dataService.getData(sourceUrl).subscribe(data => {
  this.myData = JSON.parse(data);
  console.log(this.myData);
});

}

Please let me know how to solve it and get the reference of this properly.

3
Try using .bind(this) like addEventListener("click", this.onClickRainFall.bind(this)). There are a lot of simular questions on stackoverflowyurzui
Hi yurzui: I tried this but it says Cannot read properly getdata of undefined. I didn't get a question like this. Please have a look once.Kanhaiya Choudhary
It worked. ThanksKanhaiya Choudhary

3 Answers

1
votes

Assign this to another variable before triggering the eventListener then use the new variable instead of this.

Example:

let that = this;
const marker = L.marker([lon, lat], c).addEventListener("click", function() {
    var sourceUrl2 = "a.b.c.d/" + e.sourceTarget.options.properties.abc; that.getData(sourceUrl2);
    }).addTo(map);
0
votes

you need to bind the context to the associated function.

this.onClickRainFall.bind(this)
0
votes

Perhaps a bit simpler option

const marker = L.marker([lon, lat], c).addEventListener("click", (e) => this.onClickRainFall(e)).addTo(map);

With this becoming an upvalue