Skip to content

Commit

Permalink
feat: provide the eventService class for event management
Browse files Browse the repository at this point in the history
  • Loading branch information
wewoor committed Oct 22, 2020
1 parent 03f66a5 commit d5708b5
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/services/eventService.ts
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;
};
}

0 comments on commit d5708b5

Please sign in to comment.