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.

eko
  • 39,722
  • 10
  • 72
  • 98
Jotan
  • 607
  • 1
  • 5
  • 13
  • Possible duplicate of [TypeScript 'this' scoping issue](http://stackoverflow.com/questions/42173899/typescript-this-scoping-issue) – n00dl3 Mar 28 '17 at 07:36

1 Answers1

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")
   }
 });
}
eko
  • 39,722
  • 10
  • 72
  • 98
  • 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? – Jotan Mar 28 '17 at 07:44
  • @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: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/20279485#20279485 – eko Mar 28 '17 at 07:47