avatar

ShinChven's Blog

Emit and Listen to Socket.IO Events in FeathersJS

Mon Dec 12 2022

FeatherJS uses Socket.IO to build real-time applications. With it, we can push messages from server side to client side.

Events for RESTful Service

FeathersJS has implemented basic events for RESTful service like:

  • created
  • updated
  • patched
  • removed

It is configured in src/channels.ts by default, you don't have to emit these events yourself.

Emit Event Programmatically

To emit an event programmatically for a custom service, we can use service.emit method.

app.service('messages').emit('created', { text: 'A new message' });

Emit Custom Event

If you your event is not in the events list for RESTful service, you should declare it in your service, then use it to emit event.

class Message{
  events = ['custom-event'];
}

app.service('messages').emit('custom-event', { text: 'A new message' });

Listen to Event

At client side, we can listen to event by using service.on method.

// Event for RESTful service
app.service('messages').on('created', message => console.log('Created a new message', message));
// Custom event
app.service('messages').on('custom-event', message => console.log('Custom event', message));

Remove Event Listener

To remove event listener, we can use service.removeListener method.

It is a good practice to remove event listener when your component is unmounted.

// Make a reference to the listener
const listener = message => console.log('Custom event', message);
// Mount the listener
app.service('messages').on('custom-event', listener);
// Remove the listener
app.service('messages').removeListener('custom-event', listener);