Passing This To Window.onscroll Function
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
Solution 1:
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();
}
};
}
Post a Comment for "Passing This To Window.onscroll Function"