-
Notifications
You must be signed in to change notification settings - Fork 1
/
redux-listeners.js
58 lines (46 loc) · 1.25 KB
/
redux-listeners.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict';
var redux = require('./redux.js');
var events = require('events');
var notification = new events.EventEmitter();
function createService (store, services) {
services.forEach(function (service) {
service.initialize(store.getState(),store.dispatch);
});
store.subscribe(function () {
services.forEach(function (service) {
service.update(store.getState(),store.dispatch);
});
});
}
function actionCreator (text) {
return {type:'message', text: text};
}
function reducer (state, action) {
if (action.type === 'message') {
var cloneState = state.slice();
cloneState.push(action.text);
return cloneState;
}
return state;
}
var store = redux.createStore(reducer,[]);
var simpleService = {
initialize: function (state,dispatch) {
console.log('service:initialize');
notification.on('message', this.onMessage.bind(null,state,dispatch));
},
update: function () {
console.log('service:update');
},
onMessage: function (state,dispatch,text) {
dispatch(actionCreator(text));
}
};
createService(store,[simpleService]);
// service:initialize
store.dispatch(actionCreator('start!'));
// service:update
notification.emit('message', 'hello!');
// service:update
store.getState();
// ['start!', 'hello!']