如何使用 rxjs bindCallback [英] how to use rxjs bindCallback

查看:27
本文介绍了如何使用 rxjs bindCallback的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 bindCallback 用于 mqtt-client 连接事件 (https://www.npmjs.com/package/mqtt#event-connect) 并出现错误.我做错了什么?

I'm trying to use bindCallback for mqtt-client connect-event (https://www.npmjs.com/package/mqtt#event-connect) and getting error. What am I doing wrong?

const client = mqtt.connect("...")
const clientOnObs = bindCallback(client.on)
clientOnObs('connect').subscribe(console.log)

错误

TypeError: Cannot read property '_events' of undefined
    at _addListener (events.js:203:19)
    at addListener (events.js:259:10)
    at Observable._subscribe (/Users/robert.rajakone/repos/2018_diprem/example-message-simulator/node_modules/rxjs/src/internal/observable/bindCallback.ts:215:26)
    at Observable._trySubscribe (/Users/robert.rajakone/repos/2018_diprem/example-message-simulator/node_modules/rxjs/src/internal/Observable.ts:231:19)
    at Observable.subscribe (/Users/robert.rajakone/repos/2018_diprem/example-message-simulator/node_modules/rxjs/src/internal/Observable.ts:212:14)
    at Object.<anonymous> (/Users/robert.rajakone/repos/2018_diprem/example-message-simulator/main.ts:30:24)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:442:12)

package.json

package.json

{
  "dependencies": {
    "i": "^0.3.6",
    "mqtt": "^2.18.8",
    "rxjs": "^6.4.0"
  }
}

node -v
v10.10.0

npm -v
6.5.0

推荐答案

当你想对一个对象的函数使用 bindCallback 时,你必须注意上下文.操作 bindCallback 将调用带有 apply 的函数并将 this 作为当前上下文传递.为了修复它,您可以将代码重写为:

When you want to use bindCallback on an object's function, you have to take care of the context. Operation bindCallback will invoke the function with apply and passing this as the current context. In order to fix it you can rewrite your code to:

const clientOnObs = bindCallback(client.on);
clientOnObs.call(client, 'connect').subscribe(console.log);

这篇关于如何使用 rxjs bindCallback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆