@OnEvent - event handling
Handling in-instance events with channel based

Overview

SugoiJS provides a way to emit and handle events based on channels.

Usage

Listening to event

overview

Using the @OnEvent decorator we can bind the decorated method with the event.
OnEvent(event: string, once?: boolean, channel?: string) event - Event name to bind to once - Should listen to the event once (default: false) channel - The channel name of the event tunnel (default: 'DEFAULT')

Example

1
import {OnEvent} from '@sugoi/server';
2
3
class EventHandler{
4
CHANNEL_NAME: string = 'FIRST_CHANNEL';
5
completed: boolean = false;
6
7
@OnEvent('data', false, EventHandler.CHANNEL_NAME)
8
onData(data: any){
9
if(this.completed){
10
return;
11
}
12
// handle the emitted data
13
processData(data);
14
}
15
16
@OnEvent('complete', true, EventHandler.CHANNEL_NAME)
17
onComplete(){
18
this.completed = true;
19
}
20
21
}
Copied!

Emit event

overview

Using the @sugoi/server EventEmitter class we can emit data based on channels
const emitter = new EventEmitter(channelName) channel - The channel name of the event tunnel (default: 'DEFAULT')

Example

1
const emitter = new EventEmitter('FIRST_CHANNEL');
2
emitter.emit('event', data)
Copied!

Full example

1
import {OnEvent, EventEmitter} from '@sugoi/server';
2
3
class EventHandler{
4
CHANNEL_NAME: string = 'FIRST_CHANNEL';
5
completed: boolean = false;
6
emitter: EventEmitter = new EventEmitter(EventHandler.CHANNEL_NAME);
7
8
@OnEvent('data', false, EventHandler.CHANNEL_NAME)
9
onData(data: any){
10
if(this.completed){
11
return;
12
}
13
// handle the emitted data
14
processData(data);
15
}
16
17
@OnEvent('complete', true, EventHandler.CHANNEL_NAME)
18
onComplete(){
19
this.completed = true;
20
}
21
22
emit(event: string, ...data?: any){
23
this.emitter.emit(event, ...data);
24
}
25
26
}
Copied!
Last modified 2yr ago