[英]Callback Mutation Inside Message Event
So I ran into some Javascript weirdness if i write a function like this my passed callback works fine 所以如果我写这样的函数我传递的回调工作正常,就会遇到一些Javascript怪异
messageHandler(callback) {
this.ws.onmessage = (data) => {
callback(data.data);
};
}
If you write like this 如果你这样写
messageHandler(callback) {
this.ws.on('message', (data) => {
callback(data);
});
}
It mutates the callback into a message event I can't seem to figure out why but I'd like to understand this behavior if anyone can explain. 它将回调更改为一个消息事件,我似乎无法弄清楚为什么,但是如果有人可以解释,我想了解这种行为。 Thanks in Advance.
提前致谢。
I think the question omits crucial information but based on the code examples, I think you're using https://github.com/websockets/ws implementation, correct? 我认为该问题省略了关键信息,但是基于代码示例,我认为您正在使用https://github.com/websockets/ws的实现,对吗?
If so, then .ws.on('message', ...
refers to Event Emitter listener . The params passed to your handler is the message or stream or whatever data object the emitter emits. 如果是这样,则
.ws.on('message', ...
表示事件发射器监听器 。传递给您的处理程序的参数是消息或流或发射器发射的任何数据对象。
.ws.onmessage
refers to the browser's Websocket API - so the parameter passed there is a MessageEvent . .ws.onmessage
引用浏览器的Websocket API-因此传递的参数是MessageEvent 。 As you can see from the spec, data
is a property on MessageEvent
class which explains why you have to refer with 1 level of indirection as data.data
. 从规范中可以看到,
data
是MessageEvent
类的一个属性,它解释了为什么必须将1级间接引用称为data.data
。
Perhaps it'd be less confusing if you call your parameter event
instead of data in the first example: 如果在第一个示例中调用参数
event
而不是数据,可能会减少混乱:
this.ws.onmessage = (event) => {
callback(event.data);
};
You can also view this as server side events vs. client side events - your first example is a client side event whereas the second example is a server side event. 您还可以将其视为服务器端事件与客户端事件-第一个示例是客户端事件,而第二个示例是服务器端事件。 Client side events conform to Websockets API whereas server side events, in NodeJS world, typically use event emitters.
客户端事件符合Websockets API,而NodeJS世界中的服务器端事件通常使用事件发射器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.