Answer the question
In order to leave comments, you need to log in
Why is this not available in callback?
I am making a class for pagination, using a wrapper for jquery inside it - the Request class . The getRecords method is a callback that is hung on $(window).scroll() , internally it calls the Request class to make a request, inside of which onRequest is a success callback that calls $.ajax( ). Inside onRequest , this no longer contains Pagination, but contains an object containing request data.
export class Pagination{
constructor (params? :Object){
//.. more actions
this.getRecords();
fn.setOnWindowListener('scroll','pagination',null,(e) => {this.setScrollEvent(e)});
}
private setScrollEvent = (e) :void =>{
let pos = $(e.currentTarget).scrollTop() + this.paginationHeight;
let height = $(document).height();
if(pos >= height && !this.doRequest) this.getRecords();
};
public getRecords = () :void =>{
this.doRequest = true;
//здесь this - ссылка на Pagination
return new Request({
url: this.url + this.currentPage,
type: `GET`,
dataType: this.requestDataType,
onRequest: (data) =>{
//а здесь this превратился в объект $.ajax()
this.doRequest = false;
this.currentPage++;
this.onRecordsLoaded(data);
}
}).exec();
};
}
public getRecords = (context: Pagination) :void =>{
context.doRequest = true;
return new Request({
url: context.url + context.currentPage,
type: `GET`,
dataType: context.requestDataType,
onRequest: (data) =>{
context.doRequest = false;
context.currentPage++;
context.onRecordsLoaded(context.context, data);
}
}).exec();
};
constructor (context :Object, params? :Object){
this.context = context;
Answer the question
In order to leave comments, you need to log in
The error is in Request. There, apparently, onRequest is passed to $.ajax directly, something like this:
$.ajax({
url: this.url + this.currentPage,
type: `GET`,
/*... more params */
}).done(this.onRequest);
$.ajax({
url: this.url + this.currentPage,
type: `GET`,
/*... more params */
}).done(data => this.onRequest(data))
Try to put the Request in a separate method, for example:
public ajax = (params) => new Request(params);
this.ajax({
url: this.url + this.currentPage,
type: `GET`,
dataType: this.requestDataType,
onRequest: (data) =>{
//а здесь this превратился в объект $.ajax()
this.doRequest = false;
this.currentPage++;
this.onRecordsLoaded(data);
}
})
In your example #onRequest is called in the context of $.ajax and the arrow function won't help here. In general, look at the implementation of Request
private _requestSuccess(data) =>{
this.doRequest = false;
this.currentPage++;
this.onRecordsLoaded(data);
}
public getRecords = () :void =>{
this.doRequest = true;
//здесь this - ссылка на Pagination
return new Request({
url: this.url + this.currentPage,
type: `GET`,
dataType: this.requestDataType,
onRequest: this._requestSuccess.bind(this)
}).exec();
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question