forked from carlosrocha/react-data-components
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataStore.js
93 lines (73 loc) · 2.05 KB
/
DataStore.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
89
90
91
92
93
var Dispatcher = require('./Dispatcher');
var { ActionTypes } = require('./AppConstants');
var { EventEmitter } = require('events');
var { sort, filter } = require('react-data-components').utils;
var assign = require('object-assign');
var CHANGE_EVENT = 'change';
var _rawData = [];
var _data = {};
var initVals = {
filtered: [],
page: [],
filterValues: {},
sortBy: {},
totalPages: 0,
pageNumber: 0
};
function _buildPage() {
var { pageSize, pageNumber, filtered } = _data;
var start = pageSize * pageNumber;
_data.page = filtered.slice(start, start + pageSize);
_data.totalPages = Math.ceil(filtered.length / pageSize);
}
var DataStore = assign(EventEmitter.prototype, {
addChangeListener(cb) {
this.on(CHANGE_EVENT, cb);
},
removeChangeListener(cb) {
this.removeListener(CHANGE_EVENT, cb);
},
emitChange() {
this.emit(CHANGE_EVENT);
},
init(config) {
var merged = assign(initVals, config);
_data = merged;
},
getData() {
return _data;
}
});
Dispatcher.register(action => {
switch (action.type) {
case ActionTypes.DATA_RECEIVE:
_rawData = action.data;
_data.filtered = sort(_data.sortBy, action.data);
break;
case ActionTypes.DATA_SORT:
_data.sortBy = action.sortBy;
_data.filtered = sort(action.sortBy, _data.filtered);
break;
case ActionTypes.DATA_CHANGE_PAGE_NUMBER:
_data.pageNumber = action.pageNumber;
break;
case ActionTypes.DATA_CHANGE_PAGE_SIZE:
var { pageSize } = action;
_data.pageNumber =
Math.floor((_data.pageNumber * _data.pageSize) / pageSize);
_data.pageSize = pageSize;
break;
case ActionTypes.DATA_FILTER:
var { filterName, filterValue } = action;
_data.filterValues[filterName] = filterValue;
_data.filtered = filter(_data.filters, _data.filterValues, _rawData);
_data.filtered = sort(_data.sortBy, _data.filtered);
_data.pageNumber = 0;
break;
default:
return;
}
_buildPage();
DataStore.emitChange();
});
module.exports = DataStore;