繁体   English   中英

将其他参数绑定到事件处理程序

[英]Binding additionall parameters to event handler

用例:

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

码:

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确实是您想要的,额外参数是第一个参数而不是第二个:

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

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

调用bind return函数时,它会在调用bind时使用您给它提供的所有参数来调用原始函数,然后再调用该函数。 因此,如果您bind参数A并使用参数B调用它,则原始函数将使用参数A和B调用(按此顺序)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM