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

标签 javascript node.js typescript

用例:

我有一个事件处理程序,它已经传递了一个参数(一个错误对象)。在我绑定(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/

相关文章:

javascript - Vue.js 服务器端渲染 : document is not defined

javascript - Uncaught ReferenceError : validate is not defined (jQuery validation)

html - peerConnection.addIceCandidate 给出错误 : invalid string

javascript - 无法使用 node.js v0.12.7、express 4、body-parser、bootstrap 3 检索 POST 数据

typescript - 如何像在 WebStorm 中一样轻松地导航到 VS Code 中的接口(interface)实现?

正则表达式 : Mask last 50% of string

javascript - 在没有 e.preventDefault() 的情况下禁用浏览器中的箭头键滚动

javascript - 在 .eslintrc.js 文件中使用 export default 而不是 module.exports

angularjs - 如何在 Angular 2 中使用 amcharts 的 ammaps?

reactjs - 将 react-redux useSelector 与 typescript 一起使用