2

I want to execute an exeternal function inside the JQuery method. The problem appear when I try to call the method, the one looks undefined. How could I solve this? I amb using Typescript with Angular 2

ngAfterViewInit() {

jQuery(".mo-table").scroll(function () {
  var trueDiveHeight = jQuery(".mo-table")[0].scrollHeight;
  var divHeight = jQuery(".mo-table").height();
  var scrollLeft = trueDiveHeight - divHeight;

  if (jQuery(".mo-table").scrollTop() >= scrollLeft - 150) {

    this.onSearch();

    console.log("new bottom")
   }
 });
}

The method onSearch is an external function, and is Undefined.

onSearch(): void {      
  this.updateTableReport(this.scrollId, this.buildParams())
}

Any help would be appreciated.

1

1 Answer 1

2

Change

jQuery(".mo-table").scroll(function () {

to

jQuery(".mo-table").scroll( ()=> {

your this is not refering to your component

or the old js way:

ngAfterViewInit() {

var self = this; //<-- assign this to self here
jQuery(".mo-table").scroll(function () {
  var trueDiveHeight = jQuery(".mo-table")[0].scrollHeight;
  var divHeight = jQuery(".mo-table").height();
  var scrollLeft = trueDiveHeight - divHeight;

  if (jQuery(".mo-table").scrollTop() >= scrollLeft - 150) {

    self.onSearch(); //<-- use self here

    console.log("new bottom")
   }
 });
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thank you, I didn't knew the "self" logic. Why is this working? I mean, when we assign to this, is getting the reference for the whole page?
@XGuy when you use the work function in javascript, you are creating a new scope. The this inside this scope refers to the lets say instance of this function. So this will refer to different things in and out of this function. More info on: stackoverflow.com/questions/20279484/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.