-
Notifications
You must be signed in to change notification settings - Fork 129
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: provide the eventService class for event management
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { EventEmitter } from 'mo/common/event'; | ||
|
||
export const EventService = new EventEmitter(); | ||
|
||
/** | ||
* Emit decorator, when the function be called, | ||
* it's going to notify the listener | ||
* @param name Event name | ||
*/ | ||
export function emit(name: string) { | ||
return function( | ||
target, | ||
property: string, | ||
descriptor: PropertyDescriptor, | ||
) { | ||
const original = descriptor.value; | ||
if (typeof original === 'function') { | ||
descriptor.value = function(...args) { | ||
try { | ||
const result = original.apply(this, args); | ||
EventService.emit(name, args); | ||
return result; | ||
} catch (e) { | ||
throw e; | ||
} | ||
}; | ||
} | ||
return descriptor; | ||
}; | ||
} | ||
|
||
|
||
/** | ||
* When the event emitted, it's going to call target function | ||
* @param name Event name | ||
*/ | ||
export function subscribe(name: string | string []) { | ||
return function( | ||
target, | ||
property: string, | ||
descriptor: PropertyDescriptor, | ||
) { | ||
const original = descriptor.value; | ||
if (typeof original === 'function') { | ||
EventService.subscribe(name, original); | ||
} | ||
return descriptor; | ||
}; | ||
} |