When making an ajax call with JQuery, the reference of the keyword this changes in the success callback.
In the callback function, all properties are undefined, this._ApiSrc, …
In order to access them I made a var pThis = this; before the $.ajax as those var remains defined in the success callback. This gave me a way to push object in _quotesSetIds within the callback function. Is this right?
Give the following code:
function quote(){
//Private
this._ApiSrc = "";
this._queryLimit = 30;
this._quotesSet = [];
this._quotesSetIds = [];
//Methods
this.GetQuote = function (){
/* Get a new random quotes */
this._GetQuotesSet();
};
this._GetQuotesSet = function(){
var pThis = this; //Give access path to current this.
//get a set of random quotes.
$.ajax({
url: this.GetApi(),
contentType: "application/jsonp",
data: "action=query&list=random&format=json&rnnamespace=0&prop=info&rnlimit="+this.GetQueryLimit(),
dataType: 'jsonp',
type: 'GET',
success: function(data) {
/* Push each object return to quotesSet */
for (var x = 0; x < data.query.random.length; x++){
**_>>>> HERE <<<<_** pThis._quotesSetIds.push(data.query.random[x]);
}
}
});
}
this.SetApi = function(src){
/* Set the Api source */
this._ApiSrc = src
}
this.GetApi = function(){
/* Get the Api source */
return this._ApiSrc;
}
};
var myQuote = new quote();
myQuote.SetApi("https://en.wikiquote.org/w/api.php");
myQuote.GetQuote();