HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
877 stars 142 forks source link

Mapping Events (Question) #26

Closed Ellisande closed 8 years ago

Ellisande commented 8 years ago

Looking at the documentation I don't see anything but socket.on('message', cb), which gives you {event: 'myEvent', data: {...data}}, but it doesn't seem like I can do socket.on('myEvent', cb). Am I missing a function I should know about on the socket object, or is the second pattern there not supported?

HenningM commented 8 years ago

You're right. The socket object exposed by express-ws is of this type. The ws.WebSocket type is quite low level, so to accomplish what you want to do you would have to build some kind of dispatcher on top of it.

For example:

app.ws('/', function(ws, req) {
  var dispatcher = new EventEmitter();
  ws.on('message', function(msg) {
    var msgObj = JSON.parse(msg);
    dispatcher.emit(msgObj.event, msgObj.data);
  });

  dispatcher.on('myEvent', function (payload) {
    console.log(payload);
  });
});