Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 7x 7x 7x 11x 7x 11x 13x 13x 12x 12x 12x 12x 12x 1x 13x 4x 4x 1x 1x 3x | import EventEmitter from './event-emitter';
import { isObject } from './utils'
/**
* Simple State
* @param {object} defaultState
*/
export default class SimpleState {
constructor(defaultState) {
this.__default_state = defaultState || {};
this.__emitter = new EventEmitter();
this.state = defaultState || {};
this.onSetBefore = (state) => state;
this.onSetAfter = () => {};
}
set(newState) {
return this.__setState(newState, true);
}
__setState(newState, append) {
let state = typeof newState === 'function'
? newState(this.state)
: newState;
if (isObject(state)) {
state = this.onSetBefore(state);
const prevState = Object.assign({}, this.state);
this.state = append
? Object.assign({}, this.state, state)
: Object.assign({}, state);
this.onSetAfter(this.state, newState);
this.__emitter.next(prevState, this.state);
} else {
this.__emitter.error(new TypeError(`[${this.constructor.name}] set(state) - "state" must be an object`));
}
return this.state;
}
get(key) {
Iif (key) return this.state[key];
return this.state;
}
reset() {
return this.__setState(this.__default_state, false);
}
clear() {
return this.__setState({}, false);
}
subscribe(next, props, error) {
return this.__emitter.subscribe(next, props, error);
}
} |