Traceable
Inspired by @ngrx/platform for Angular applications, this library allows you to decorate any prototype / class with a functionality to track object states created from it as an event stream using Reactive Extension observables, see ReactiveX/rxjs.
It's also possible to create side effects in the prototype level that runs automatically when the state of an object has changed or we're trying to make some actions on it.
Setup
Please make sure you know what reactive programming means and you are familiar with the rxjs library first in order to use the Observable interface:
Install our library:
npm i trace-state
Usage
Check out our pre maid Examples to get sense of how to use this library properly.
using Traceable decorator:
the Traceable decorator adds functionality to a class / prototype (check type Traceable<STATE, ACTIONS>) so when an object of this prototype is created, you can track its changes.
in order to use decorators in Typescript you should enable experimentalDecorators compiler option in your tsconfig.json file like so:
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
Create a person object and track it's state:
interface PersonData {
age: string;
}
interface PersonOlderAction extends Action {
type = 'older';
constructor() {
}
}
type PersonActions = PersonOlderAction;
function reducer(action: PersonActions, previous_state: PersonData) {
if (action.type === 'older') {
return {
age: previous_state.age + 1
};
}
return previous_state;
}
function initialize() {
return {
age: 0
}
}
@Traceable<PersonData, PersonActions>({
reduce: reducer,
initialize: initialize
})
class Person {
....
older() {
this.act(new PersonOlderAction());
}
}
let person = new Person();
let personAge = person.state$('age');
personAge.subscribe(console.log);
person.older();
person.act(new PersonOlderAction());