I have this code:
function API() {
this.status = 'nothing';
}
API.prototype.search = function() {
this.status = 'searching';
$.ajax({
url: 'https://api.com',
data: {shapeFormat: 'raw'},
dataType: 'json',
timeout: 11000,
success: this.OK_callback,
error: this.KO_callback
});
}
API.prototype.OK_callback = function(data) {
console.log(this.status); // How to pass this value to the function?
}
API.prototype.KO_callback() {
this.status = 'done';
}
How could I access to this.status
value insie OK_callback
?
Thanks in advance!
You need to invoke your function in proper context. The simple is to use Function.prototype.bind method:
$.ajax({
url: 'https://api.com',
data: {shapeFormat: 'raw'},
dataType: 'json',
timeout: 11000,
success: this.OK_callback.bind(this),
error: this.KO_callback.bind(this)
});
or you can use context setting to set callback context:
$.ajax({
url: 'https://api.com',
data: {shapeFormat: 'raw'},
dataType: 'json',
timeout: 11000,
success: this.OK_callback,
error: this.KO_callback,
context: this
});