UNPKG

1.62 kBJavaScriptView Raw
1var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
2
3function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4
5/**
6 * Default store that keeps state in a simple object.
7 */
8var DefaultStore = function () {
9 function DefaultStore() {
10 _classCallCheck(this, DefaultStore);
11
12 this.state = {};
13 this.callbacks = [];
14 }
15
16 DefaultStore.prototype.getState = function getState() {
17 return this.state;
18 };
19
20 DefaultStore.prototype.setState = function setState(patch) {
21 var prevState = _extends({}, this.state);
22 var nextState = _extends({}, this.state, patch);
23
24 this.state = nextState;
25 this._publish(prevState, nextState, patch);
26 };
27
28 DefaultStore.prototype.subscribe = function subscribe(listener) {
29 var _this = this;
30
31 this.callbacks.push(listener);
32 return function () {
33 // Remove the listener.
34 _this.callbacks.splice(_this.callbacks.indexOf(listener), 1);
35 };
36 };
37
38 DefaultStore.prototype._publish = function _publish() {
39 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
40 args[_key] = arguments[_key];
41 }
42
43 this.callbacks.forEach(function (listener) {
44 listener.apply(undefined, args);
45 });
46 };
47
48 return DefaultStore;
49}();
50
51module.exports = function defaultStore() {
52 return new DefaultStore();
53};
\No newline at end of file