File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ export class EventEmitter {
2
+ private _events = new Map < string , Function [ ] > ( ) ;
3
+
4
+ public emit < ArgsType = any > ( name : string , args : ArgsType ) {
5
+ const events = this . _events . get ( name ) ;
6
+ if ( events && events . length > 0 ) {
7
+ // The log for development
8
+ console . log ( 'event emit:' , name , args ) ;
9
+ events . forEach ( ( callEvent ) => {
10
+ callEvent ( args ) ;
11
+ } ) ;
12
+ }
13
+ }
14
+
15
+ public subscribe < T = any > ( name : string | string [ ] , callback : Function ) {
16
+ if ( Array . isArray ( name ) ) {
17
+ name . forEach ( ( key : string ) => {
18
+ this . assignEvent ( key , callback ) ;
19
+ } ) ;
20
+ } else {
21
+ this . assignEvent ( name , callback ) ;
22
+ }
23
+ // The log for development
24
+ console . log ( 'event on:' , name ) ;
25
+ }
26
+
27
+ public assignEvent < T > ( name : string , callback : Function ) {
28
+ const event = this . _events . get ( name ) ;
29
+ if ( event ) {
30
+ event . push ( callback ) ;
31
+ } else {
32
+ this . _events . set ( name , [ callback ] ) ;
33
+ }
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments