Reputation: 18534
Use case:
I've got an event handler which already gets passed one parameter (an error object). At the place where I am binding the event handler I'd like to pass an additional parameter. I know there is the bind()
method, but I think I would overwrite the existing error parameter.
Code:
const client = new RequestClient(...);
// Here I want to bind the client object so that onClientError gets the
// error and the client object passed
client.onError(this.onClientError);
private onClientError = (error: Error): void => {
this.logger.error(`Error on client occured: ${error}`);
};
// And this is how I'd like to use my new event handler
private onClientError = (error: Error, client: RequestClient): void => {
this.logger.error(`Error on client occured: ${error}`);
};
My question:
How can I bind additional parameters to an event handler if it already has an existing parameter?
Upvotes: 0
Views: 45
Reputation: 1074979
bind
is indeed what you want if you're okay with the extra parameter being the first parameter instead of the second:
client.onError(this.onClientError.bind(null, client));
private onClientError = (client: RequestClient, error: Error): void => {
this.logger.error(`Error on client occured: ${error}`);
};
When the function bind
returns is called, it calls the original function with any arguments you give it when calling bind
followed by the ones it was called with. So if you bind
argument A and it gets called with argument B, the original function is called with arguments A and B (in that order).
If it has to be second, the simplest thing is a wrapper function:
client.onError(event => this.onClientError(event, client));
Upvotes: 2