@xialvjun/state
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

state

An EventEmitter which is stateful and has setState method which can debounce change event. Like Flux.

Install

npm i @xialvjun/state or yarn add @xialvjun/state

Example

import { State } from '@xialvjun/state';

class AuthState extends State<{ logined: boolean }> {
  state = { logined: false }
  other_property = 123
  async login(username, password) {
    await Promise.resolve(1);
    this.setState({ logined: true });
  }
}

const auth = new AuthState();

const unsubscribe = auth.onChange(() => {
  console.log(auth.state);
});

auth.login('xialvjun', 'password');

const on_other_event = () => {
  console.log('other_evnet', auth.other_property);
}
auth.on('other_event', on_other_event);
auth.other_property = auth.other_property + 1;
auth.emit('other_event');

unsubscribe();


interface Counter<T> extends State<T> {
  inc?(): void;
  dec?(): void;
}
const counter_state = new State({ count: 0 });
const counter = counter_state as Counter<typeof counter_state.state>
counter.inc = () => counter.setState({ count: counter.state.count + 1 });
counter.dec = () => counter.setState({ count: counter.state.count - 1 });

Readme

Keywords

Package Sidebar

Install

npm i @xialvjun/state

Weekly Downloads

1

Version

0.0.3

License

MIT

Unpacked Size

26.1 kB

Total Files

12

Last publish

Collaborators

  • xialvjun