Binding a function to event
Listening to events become simple with decorators

Overview

SugoiJS provide single line binding solution for binding a class method to socket event

Bind socket events

Listening to socket events become simple with @SocketOn decorator
1
@SocketOn(event: string, namespace: string = "/", ...middlewares:Array<ISocketMiddleware>)
Copied!
event - The event name namespace - The related namespace which the socket should be related to. middlewares - 0...n arguments of middleware functions which should occur before the event callback function.
Another signature of this decorator is:
1
@SocketOn(event: string, ...middlewares:Array<ISocketMiddleware>)
Copied!
1
type ISocketMiddleware = (socket:SocketIOStatic.Socket,data:any)=>Promise<any>|any
Copied!
This decorator registers the function as a callback for an event. In case middlewares functions were passed, those methods will occur right before the callback function.

Example

1
@SocketOn("message","/",(socket,data)=>{
2
console.log("log message data: %s from socket id: %s",data,socket.id);
3
})
4
function messageHandler(socket,data){
5
socket.to(data.room).emit('message',data.message)
6
}
Copied!
You can bind one function to multiple events by use multiple @SocketOn decorators.

Bind Server events

Listening to Socket events become simple with @SocketServerOn decorator
1
@SocketServerOn(event: string, namespace: string = "/", ...middlewares:Array<ISocketMiddleware>)
Copied!
event - The event name namespace - The related namespace which the socket should be related to. middlewares - 0...n arguments of middleware functions which should occur before the event callback function.
Another signature of this decorator is:
1
@SocketServerOn(event: string, ...middlewares:Array<ISocketMiddleware>)
Copied!
1
type ISocketMiddleware = (socket:SocketIOStatic.Socket,data:any)=>Promise<any>|any
Copied!
This decorator registers the function as a callback for an event. In case middlewares functions were passed, those methods will occur right before the callback function.

Example

1
@SocketSererOn("connection","/",(socket,data)=>{
2
console.log("log message data: %s from socket id: %s",data,socket.id);
3
})
4
function messageHandler(socket){
5
socket.emit('connected',{msg:"welcome"})
6
}
Copied!
You can bind one function to multiple events by use multiple @SocketServerOn decorators.
Last modified 2yr ago