gpt4 book ai didi

javascript - 将附加参数绑定(bind)到事件处理程序

转载 作者:行者123 更新时间:2023-12-01 02:05:48 25 4
gpt4 key购买 nike

用例:

我有一个事件处理程序,它已经传递了一个参数(一个错误对象)。在我绑定(bind)事件处理程序的地方,我想传递一个附加参数。我知道有 bind() 方法,但我想我会覆盖现有的错误参数。

代码:

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}`);
};

我的问题:

如果事件处理程序已有参数,如何将其他参数绑定(bind)到该事件处理程序?

最佳答案

bind 确实是您想要的如果您同意将额外参数作为第一个参数而不是第二个:

client.onError(this.onClientError.bind(null, client)); 

private onClientError = (client: RequestClient, error: Error): void => {
this.logger.error(`Error on client occured: ${error}`);
};

当调用函数 bind 返回时,它会使用您在调用 bind 时提供的任何参数来调用原始函数,后跟调用它时使用的参数。因此,如果您绑定(bind)参数 A 并且使用参数 B 调用它,则使用参数 A 和 B(按该顺序)调用原始函数。

如果必须是第二个,最简单的是包装函数:

client.onError(event => this.onClientError(event, client));

关于javascript - 将附加参数绑定(bind)到事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50120313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com