-
Notifications
You must be signed in to change notification settings - Fork 491
Open
Description
Issue
As of the current version, the library registers events by overriding the Socket's onevent handler. Snippet:
/**
* Listening all socket.io events
*/
register(){
this.io.onevent = (packet) => {
let [event, ...args] = packet.data;
if(args.length === 1) args = args[0];
this.onEvent(event, args)
};
VueSocketIOListener.staticEvents.forEach(event => this.io.on(event, args => this.onEvent(event, args)))
}
This is problematic as it prevents socket messages from being listened to in other parts of the code.
For example, with the existing implementation it's not possible to write:
socket.on('myEvent', () => { console.log('#myEvent received') } );
Solution
If using Socket.IO > v3.x.x, use the ``socket.onAny` Reference to listen to all and pass it along to the internal emitter.
Example
export default class VueSocketIOListener {
/**
* Reserved Socket.IO event names.
* @type {string[]}
*/
static reservedEvents = [
'connect',
'error',
'disconnect',
'reconnect',
'reconnect_attempt',
'reconnecting',
'reconnect_error',
'reconnect_failed',
'connect_error',
'connect_timeout',
'connecting',
'ping',
'pong'
];
static io = null;
static emitter = null;
constructor( io, emitter ) {
this.io = io;
this.emitter = emitter;
this.registerEvents();
}
/**
* Attach listeners for all events, including reserved events.
*/
registerEvents() {
// Intercept all events with onAny
this.io.onAny( ( event, ...args ) => {
this.handleEvent( event, args );
} );
// Register listeners for Socket.IO's reserved events
VueSocketIOListener.reservedEvents.forEach( ( event ) => {
this.io.on( event, ( args ) => this.handleEvent( event, args ) );
} );
}
/**
* Emit (broadcast) events to the emitter instance.
* @param {string} event - Event name
* @param {*} args - Payload for the event
*/
handleEvent( event, args ) {
this.emitter.emit( event, args );
}
}
Metadata
Metadata
Assignees
Labels
No labels