Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lodash debounce in Angular2 & Typescript scroll not working

I have the following code which calls a lodash debounce function:

@HostListener("window:scroll", [])
onWindowScroll() {
    if (myBoolean) 
       _.debounce(this.onScrollDown(), 1500, false);

    }
}

private onScrollDown() {
    console.log("onScrollDown")
}

But I'm getting this error in my console:

Argument of type 'void' is not assignable to parameter of type 'Function'.

And the following on browser:

TypeError: Expected a function
    at Function.debounce 

I'm using typescript by the way

like image 944
CommonSenseCode Avatar asked Nov 18 '16 22:11

CommonSenseCode


2 Answers

I'm not familiar with lodash, but I think what you want is:

private debouncedOnScroll = _.debounce(() => this.onScrollDown(), 1500, {});

@HostListener("window:scroll", [])
onWindowScroll() {
    this.debouncedOnScroll();
}

private onScrollDown() {
    console.log("onScrollDown")
}
like image 166
JB Nizet Avatar answered Sep 21 '22 13:09

JB Nizet


Thanks to JB Nizet I could solve my need this is my approach:

1) Create function you want to debounce:

private projectsLoad(myParameter): void {
   // function code here...
};

2) Assign it to a field/member of the class:

private debounceProjectsLoad = _.debounce(
    (myParameter) => this.projectsLoad(myParameter),
    1500,
    true
);

3) Call the debounced field/meber when neeeded:

public loadProjectsGroup(myParameter: string): void {
    this.debounceProjectsLoad(myParameter);
}
like image 24
CommonSenseCode Avatar answered Sep 21 '22 13:09

CommonSenseCode