forked from vasanthk/react-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.flux-pattern.jsx
87 lines (81 loc) · 2.12 KB
/
23.flux-pattern.jsx
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Flux pattern for data handling
*
* @Reference:
* https://github.com/krasimir/react-in-patterns/tree/master/patterns/flux
*/
// Simple dispatcher
var Dispatcher = function () {
return {
_stores: [],
register: function (store) {
this._stores.push({store: store});
},
dispatch: function (action) {
if (this._stores.length > 0) {
this._stores.forEach(function (entry) {
entry.store.update(action);
});
}
}
}
};
// We see the we expect the store to have an update method(), so let's modify register to expect it.
function register(store) {
if (!store || !store.update && typeof store.update === 'function') {
throw new Error('You should provide a store that has an updte method');
} else {
this._stores.push({store: store});
}
}
// Full blown Dispatcher
var Dispatcher = function () {
return {
_stores: [],
register: function (store) {
if (!store || !store.update) {
throw new Error('You should provide a store that has an `update` method.');
} else {
var consumers = [];
var change = function () {
consumers.forEach(function (l) {
l(store);
});
};
var subscribe = function (consumer, noInit) {
consumers.push(consumer);
!noInit ? consumer(store) : null;
};
this._stores.push({store: store, change: change});
return subscribe;
}
return false;
},
dispatch: function (action) {
if (this._stores.length > 0) {
this._stores.forEach(function (entry) {
entry.store.update(action, entry.change);
});
}
}
}
};
module.exports = {
create: function () {
var dispatcher = Dispatcher();
return {
createAction: function (type) {
if (!type) {
throw new Error('Please, provide action\'s type.');
} else {
return function (payload) {
return dispatcher.dispatch({type: type, payload: payload});
}
}
},
createSubscriber: function (store) {
return dispatcher.register(store);
}
}
}
};