ActionsWorker
Typescript class to store an immutable state that can be edited
using actions, and emits JSON props on state change.
The EntryLoader
uses it to generate a Web Worker automatically
as part of the JSON Entries system for Webpack,
but this package can also be used on its own, even without a Web Worker.
Install:
npm install @wildpeaks/actions-worker
Example:
import {ActionsWorker, IDispatcher} from '@wildpeaks/actions-worker';
type State = {
readonly count: number;
};
type Props = {
readonly text: string;
};
enum Actions {
ADD = 'add',
SUBTRACT = 'subtract'
}
type AddMessage = {
action: Actions.ADD;
delta: number;
};
type SubtractMessage = {
action: Actions.SUBTRACT;
delta: number;
};
type Messages = AddMessage | SubtractMessage;
type Dispatcher = IDispatcher<State, Messages>;
function add(message: AddMessage, dispatcher: Dispatcher): void {
const oldState: State = dispatcher.state;
const newState: State = {
count: oldState.count + message.delta
};
dispatcher.state = Object.freeze(newState);
}
function subtract(message: SubtractMessage, dispatcher: Dispatcher): void {
const oldState: State = dispatcher.state;
const newState: State = {
count: oldState.count - message.delta
};
dispatcher.state = Object.freeze(newState);
}
class Storage extends ActionsWorker<Props, State, Messages> {
constructor() {
super();
this.actions[Actions.ADD] = add;
this.actions[Actions.SUBTRACT] = subtract;
}
protected serialize(state: State): Props {
const props: Props = {
text: `Count is ${state.count}`
};
Object.freeze(props);
return props;
}
}
const store = new Storage();
store.onprops = props => {
console.log(props);
};
store.state = {
count: 0
};
store.schedule({
action: Actions.ADD,
delta: 1
});
store.schedule({
action: Actions.ADD,
delta: 10
});
store.schedule({
action: Actions.SUBTRACT,
delta: 200
});