Emit and Listen to Socket.IO Events in FeathersJS
FeatherJS uses Socket.IO to build real-time applications. With it, we can push messages from server side to client side.
FeathersJS has implemented basic events for RESTful service like:
It is configured in src/channels.ts
by default, you don't have to emit these events yourself.
To emit an event programmatically for a custom service, we can use service.emit
method.
app.service('messages').emit('created', { text: 'A new message' });
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' });
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));
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);