-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathdispatch.ts
43 lines (40 loc) · 1.29 KB
/
dispatch.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
39
40
41
42
43
import { NgRedux } from '../components/ng-redux';
import { getBaseStore } from './helpers';
/**
* Auto-dispatches the return value of the decorated function.
*
* Decorate a function creator method with @dispatch and its return
* value will automatically be passed to ngRedux.dispatch() for you.
*/
export function dispatch(): PropertyDecorator {
return function decorate(
target: Object,
key: string | symbol | number,
descriptor?: PropertyDescriptor
): PropertyDescriptor {
let originalMethod: Function;
const wrapped = function(this: any, ...args: any[]) {
const result = originalMethod.apply(this, args);
if (result !== false) {
const store = getBaseStore(this) || NgRedux.instance;
if (store) {
store.dispatch(result);
}
}
return result;
};
descriptor = descriptor || Object.getOwnPropertyDescriptor(target, key);
if (descriptor === undefined) {
const dispatchDescriptor: PropertyDescriptor = {
get: () => wrapped,
set: setMethod => (originalMethod = setMethod),
};
Object.defineProperty(target, key, dispatchDescriptor);
return dispatchDescriptor;
} else {
originalMethod = descriptor.value;
descriptor.value = wrapped;
return descriptor;
}
};
}