Peter Boomsma
Peter Boomsma

Reputation: 9844

Function is not a function during addEventListener

I'm running an Angular 1.5 project with TypeSCript and I'm running into some bugs. I want to check the scrollTop value from the .uc-card element.

public container = document.querySelector(".uc-card");

In my $onInit I have:

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
     
    this.container.addEventListener('scroll', function() {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

    });
}

And I have 2 functions, scroll and doSomething:

private doSomething() {
    console.log('doSomething');
}

private scroll(e) {
    console.log('scroll')
    console.log(e.scrollTop);
    console.log(this.container.scrollTop);
}

When I run the application I get the following in the console log:

scroll
0
0
doSomething

This works fine. I returns the scrollTop value of my .uc-card element. But when I scroll I get the following:

scrollOnInit

CustomerActivitiesComponent.ts:38 Uncaught TypeError: this.doSomething is not a function HTMLDivElement. (CustomerActivitiesComponent.ts:38)

The scroll function does work since the output shows scrollOnInit. But the scroll function is not called (or at least does not show any ouput) and the doSomething method isn't a function. But they all work fine in the onInit.

Upvotes: 2

Views: 262

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92334

Use an arrow function, =>. The regular function syntax does not keep the same this as the outside.

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
    // Setting event handler with arrow function guarantees `this` will be
    // the same as this it is here
    // It is like setting const _this = this, and using _this within the 
    // regular function
    this.container.addEventListener('scroll', () => {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

    });
}

Upvotes: 2

Related Questions