I have a simple class which extends the EventEmitter
object from node:events
, like this:
export class SimpleService extends EventEmitter {
constructor() {
super();
}
execute() {
try {
const webSocket = new WebSocket('wss://server-socket:1234');
webSocket.onopen = function () {
this.emit('data', 'Web socket connection is opened...');
};
} catch (error) {
this.emit('error', error);
}
}
The execute method created the WebSocket, and when it is opened, I emit this information. The client is like this:
const simpleService = new SimpleService();
simpleService
.on('error', (error) => {
console.log('ERRORRR');
})
.on('data', (data) => {
console.log(data);
})
.execute();
but when I run it, it does not show the data emitted from the service, if they are inside webSocket methods.
I just needed to change
webSocket.onopen = function () {
this.emit('data', 'Web socket connection is opened...');
};
into
webSocket.on('open',() => {
this.emit('data', 'Web socket connection is opened...');
});
What is the reason for this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.