Search code examples
javascripttypescriptlodash

using flush on lodash's throttle decorator


Using TypeScript (JavaScript and Angular):

I want lodash's throttle decorator to limit an API call while the user is navigating around the page, but still fire before they unload (leave) the site.

In the typescript constructor I have window.addEventListener('beforeunload', () => this.onUnload());

with the onUnload() function being declared as

onUnload() {
    this.thisIsTheThrottledFunction.flush;
}

but I am getting the error response "Property 'flush' does not exist on type '() => Promise'."

The function whose .flush method I am trying to access is the declared throttled version of the other function. The function is successfully throttled, so I am confident that part of the code works. What is the best way to access the .flush method?


Solution

  • You should be able to debug this by verifying what the value of this is. Seems to me like you just need to bind the object's this value to the onUnload function (or you can pass it in). For instance, you could put this in your constructor: this.onUnload = this.onUnload.bind(this). There's a sugar for this syntax, where you define it in your class using onUnload = () => { ... }. Both of those methods attach the method to the instance instead of just having it as part of the prototype. Or, you could pass the bound function directly to your event listener:

    window.addEventListener('beforeunload', this.onUnload.bind(this));