I'm working on a TVML/TVJS app and have run into an issue when working with classes in Javascript.
My starting application.js file calls a function
resourceLoader = new ResourceLoader();
resourceLoader.getHomeScreen();
I have a separate file called ResourceLoader.js with the following:
class ResourceLoader {
getHomeScreen() {
var homeData = BASEURL + "/home.json";
var homeTemplate = BASEURL + "/home.tvml";
this.getRemoteJSON(homeData, homeTemplate, this._jsonLoaded);
}
_jsonLoaded(template, jsonString) {
var parsedJSON = JSON.parse(jsonString);
this.getRemoteXMLFile(template, parsedJSON);
}
getRemoteJSON(file, template, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.addEventListener("load", function() {
callback(template, xhr.responseText);
}, false);
xhr.open("GET", file, true);
xhr.send();
}
getRemoteXMLFile(template, json) {
var xhr = new XMLHttpRequest();
xhr.responseType = "xml";
xhr.addEventListener("load", function() {
loadRemoteFile(xhr.responseText, json);
}, false);
xhr.open("GET", template, true);
xhr.send();
}
}
(BASEURL is a global variable defined in application.js)
Everything works fine in the beginning. getHomeScreen() is called, it manages to call getRemoteJSON() and pass _jsonLoaded() as the callback. getRemoteJSON does the AJAX call and then runs the callback. This is where the issue happens. Once inside _jsonLoaded, "this" becomes undefined, so when I call this.getRemoteXMLFile, I get the error message "undefined is not an object (evaluating 'this.getRemoteXMLFile')"
Why was "this" working in getHomeScreen() but not in _jsonLoaded()? How can I access my getRemoteXMLFile function from _jsonLoaded()?
Thanks for any help.
That is because callback is not a function.
A good solution would be to use ES6 Promises.
Here's an example fetching data using AJAX with a Promise
And how to call it