0.1.1 • Published 6 years ago

@honkjs/publisher v0.1.1

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
6 years ago

honkjs/publisher

Single event type publisher. Allows for type safe custom arguments publishing.

Example

import { Publisher } from '@honkjs/publisher';

// the type of function can be anything that returns void or boolean.
// any other params are allowed.
type MyEvent = (a: string, b: number) => void;

const event = new Publisher<MyEvent>();

const unsub = event.subscribe((a, b) => {
  console.log('published', a, b);
});

event.publish('hello', 5); // output: published, hello, 5

unsub();

event.publish('hello?', 0); // output: nothing

Creating a store

Let's build out a store that generates events when the state is changed.

import { Publisher } from '@honkjs/publisher';

export function createStore<S>(initialState: S) {
  let state = initialState;
  let events = new Publisher<(state: S) => void>();

  return {
    setState: (action) => {
      state = action(state);
      events.publish(state);
    },
    getState: () => state,
    subscribe: (listener) => events.subscribe(listener),
  };
}

const state = { data: 'test' };

const store = createStore(state);

const unsub = store.subscribe((s) => {
  console.log('updated', s);
});

store.setState({ data: 'different' });
// outputs: updated, { data: different }

unsub();

This functionality is built for you in @honkjs/store.