UNPKG

1.74 kBJavaScriptView Raw
1import {
2 createStore,
3 applyMiddleware,
4} from 'redux';
5import makePropTypesDirective from './directive-proptypes';
6
7const ActionTypes = {
8 INIT: '@@redux/INIT',
9};
10
11/**
12 *
13 * @param app {{angular}}
14 */
15function angularSetup(app) {
16 /**
17 * understanding angular provider: https://www.evernote.com/shard/s16/sh/93652e36-4492-438d-94e3-86714b8ed49e/d885f65c9a74675c3d22cb4ff1d9df56
18 */
19 app.provider('ngStore', function () { // because we need the context `this`
20 let state = {};
21 let currentUpdater = currentState => currentState;
22 let dispatchLayers = [];
23
24
25 this.setInitialState = initialState => {
26 state = initialState;
27 };
28
29 this.setReducers = this.putUpdaters = updater => {
30 currentUpdater = updater;
31 };
32
33 this.putLayers = layers => {
34 dispatchLayers = layers;
35 };
36
37 this.$get = ['$timeout',
38 function ($timeout) {
39 function digestAngularUI() {
40 return (nextLayer) => (action) => {
41 let result;
42 try {
43 result = nextLayer(action);
44 } catch (e) {
45 console.error('DISPATCH ERROR >>> ', e);
46 }
47
48 // update the UI on angular, make sure changes in state will be in the $digest circle
49 $timeout(() => result);
50 return result;
51 };
52 }
53
54 dispatchLayers.unshift(digestAngularUI);
55
56 const finalStore = createStore(currentUpdater, state, applyMiddleware(...dispatchLayers));
57
58 return finalStore;
59 }];
60 });
61
62
63 app.run(['ngStore', (store) => {
64 store.dispatch({
65 type: ActionTypes.INIT,
66 });
67 }]);
68
69 app.directive = makePropTypesDirective(app.directive.bind(app));
70
71 return app;
72}
73
74export default angularSetup;