I don't understand JavaScript scope when it comes to object variables. I have the following class defined:
class DataHandler {
constructor(boardIDA, boardIDB, accessToken, eventA, eventB) {
this.times = [];
this.eventA = eventA;
this.eventB = eventB;
this.apiURLA = "https://api.particle.io/v1/devices/" + boardIDA + "/events/" + eventA + "/?access_token=" +
accessToken;
this.apiURLB = "https://api.particle.io/v1/devices/" + boardIDB + "/events/" + eventB + "/?access_token=" + accessToken;
this.eventListenerA = new EventSource(this.apiURLA);
this.eventListenerB = new EventSource(this.apiURLB);
this.addListener(this.eventListenerA,
eventA);
this.addListener(this.eventListenerB, eventB);
}
addListener(eventSrc, eventName) {
eventSrc.addEventListener(eventName, function(info) {
alert(eventName);
var parsedData = JSON.parse(info.data);
this.times.push(parsedData);
});
}
}
The issue is with this.times
. I have declared it in the constructor. However, I can't seem to access it in addListener
— I get an error saying that I'm trying to call push
on undefined
. What am I doing wrong?