Skip to content

honkjs/publisher

Repository files navigation

honkjs/publisher

Greenkeeper badge

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

Canceling

Event handlers are always fired in the order they were added.

If a handler returns true, publisher will cancel publishing to handlers after that one.

event.subscribe((a, b) => {
  if (b > 5) return true; // handled
});

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

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

event.publish('hello?', 10); // 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((s) => ({ data: 'different' }));
// outputs: updated, { data: different }

unsub();

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