/
lib.js
88 lines (70 loc) · 2.44 KB
/
lib.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
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
88
'use strict';
var assign = require('object-assign');
var Store = require('./store');
var StateMixin = require('./state-mixin');
var eventEmitter = require('events').EventEmitter;
function Flux(options) {
if (!(this instanceof Flux))
return new Flux(options);
options = options || {};
this.Stores = {};
this.Actions = {};
this.Dispatcher = new eventEmitter();
this.context = {};
this.context.Stores = this.Stores;
this.context.Actions = this.Actions;
this.context.Dispatcher = this.Dispatcher;
this.context.shouldUpdate = true;
if (options.Stores)
this.registerStores(options.Stores);
if (options.Actions)
this.registerActions(options.Actions);
if (options.Actors && options.socket)
this.registerSocketActors(options.socket, options.Actors);
}
Flux.prototype.registerStore = function(name, storeDefinition) {
this.Stores[name] = Store(storeDefinition, this.context);
};
Flux.prototype.registerStores = function(storeDefinitions) {
Object.keys(storeDefinitions).forEach(function(store) {
this.registerStore(store, storeDefinitions[store]);
}.bind(this));
};
Flux.prototype.registerAction = function(name, actionCreator) {
this.Actions[name] = actionCreator.bind(null, this.context);
};
Flux.prototype.registerActions = function(actionCreators) {
Object.keys(actionCreators).forEach(function(creator) {
this.registerAction(creator, actionCreators[creator]);
}.bind(this));
};
Flux.prototype.registerSocketActor = function(socket, event, eventActor) {
socket.on(event, eventActor.bind(null, this.context));
};
Flux.prototype.registerSocketActors = function(socket, eventActorDefinitions) {
Object.keys(eventActorDefinitions).forEach(function(event) {
this.registerSocketActor(socket, event, eventActorDefinitions[event]);
}.bind(this));
};
Flux.prototype.getContext = function() {
return this.context;
};
Flux.prototype.addToContext = function(name, obj) {
this.context[name] = obj;
};
Flux.prototype.dehydrate = function() {
return Object.keys(this.Stores).reduce(function(appState, Store) {
appState[Store] = this.Stores[Store].getState();
return appState;
}.bind(this), {});
};
Flux.prototype.rehydrate = function(appState) {
Object.keys(this.Stores).forEach(function(Store) {
this.Stores[Store].replaceState(appState[Store])
}.bind(this));
};
Flux.prototype.enableUpdates = function(cond) {
this.context.shouldUpdate = !!cond;
};
Flux.StateMixin = StateMixin;
module.exports = Flux;