Behaviour after scroll event

2019-09-08 14:56发布

问题:

I have a problem using Angular2. If I'm not mistaken in Angular2 I should put my code in class instead of controller and access variables by this but I have a variable I want to access from function assigned to window.onscroll, and this inside this function doesn't work, because it return window.

How can I access my variables or functions on scroll event?

class someClass{

    someVariable;

    ngOnInit() {
        this.someVariable = {}; 

        window.onscroll = function() {

            // here I want to access someVariable or someFunction

        }
    }

    someFunction() {
    }

}

回答1:

I see several way to do that:

1) Using HostListener:

@HostListener('window:scroll') onScroll() {
  console.log(this.someVariable);
}

2) Using arrow function:

window.onscroll = _ => {
  console.log(this.someVariable);
};

3) Using of Function.prototype.bind():

window.onscroll = function() {
  console.log(this.someVariable);
}.bind(this);

4) Keep context in a variable like self or that:

let self = this;
window.onscroll = function() {
  console.log(self.someVariable); // <== notice self instead of this
};