0

How can I pass this to a function assigned to my window.onscroll event?

I am trying to trigger myFunction() when a certain condition is met. I need to check this condition onscroll

  init() {
    window.onscroll = function() {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }

However I get an error that this.currentItemCount() is not a function. I know that I need to pass this to window.onscroll but I cannot figure out the correct syntax.

Francesca
  • 26,842
  • 28
  • 90
  • 153
  • Using [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) sounds like the way to go – George Jan 09 '18 at 12:06

2 Answers2

5

You can use that = this construct. (What does 'var that = this;' mean in JavaScript?)

init() {
    var that = this;
    window.onscroll = function() {
      if(that.currentItemCount() > that.totalElements){
        that.totalElements = that.currentItemCount();
        that.myFunction();
      }
    };
  }

Or even better use arrow function which preserves this from the wrapping context (ES6 support or transpiler required):

init() {
    window.onscroll = () => {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }
croraf
  • 4,332
  • 2
  • 31
  • 50
1

You can try this:

init() {
    var self = this;
    window.onscroll = function() {
      if(self.currentItemCount() > self.totalElements){
        self.totalElements = self.currentItemCount();
        self.myFunction();
      }
    };
  }

this isn't available from the inner scope, but self will be available.

Anatoly
  • 5,056
  • 9
  • 62
  • 136