/
decorator.ts
38 lines (36 loc) · 1.11 KB
/
decorator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { EventBus } from './eventBus';
/**
* 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);
EventBus.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') {
EventBus.subscribe(name, original);
}
return descriptor;
};
}