I'm doing my Javascript studies, and I'm doing some pretty simple to consume an API, but I got an error. Before commenting, I'll show you my code:
View.js
var model = new Model();
var response = null;
model.setUrl("https://jsonplaceholder.typicode.com/users");
model.openXhr("GET");
Model.js
var Model = function() {
var _url = null;
var _xhr = new XMLHttpRequest();
var _message = {};
var _response = null;
this.setUrl = function (url) {
_url = url;
}
this.getUrl = function (url) {
return _url;
}
this.openXhr = function(method) {
_xhr.open(method, this.getUrl());
_xhr.onload = this.onLoadXhr;
_xhr.send();
}
this.onLoadXhr = function() {
if (_xhr.status === 200)
_message.status = "success";
else
_message.status = "failed";
var response = this.parseResponse(_xhr.responseText); // this.parseResponse is not a function
this.setResponse(response);
}
this.parseResponse = function(response) {
return JSON.parse(response);
}
this.setResponse = function(response) {
_response = response;
}
this.getResponse = function() {
return _response;
}
}
The problem
var response = this.parseResponse(_xhr.responseText); // this.parseResponse is not a function
Notice that it arrives in this part it gives this error when calling the function. By printing this
I checked that it is not from the context of the function, but from _xhr
. Because ? In another part of the code I do a similar operation and this does not happen _xhr.onload = this.onLoadXhr;
. Here I have referenced onLOadXhr
within openXhr
.