lukeed/vegemite

Listen to multiple events

Closed this issue · 1 comments

akzhy commented

Hi,
Is it possible to listen to multiple specific events from a single listen?

I would like to do something like this

const removeAppStoreListener = appStore.listen((['event-1','event-2']) => setState());

Hey, thanks for the question.

It isn't sorry. It's intentionally a single event per on() call. You can define the callback/function though and use it twice, though. The idea is that you should have full granular control over what's going on at all times. Batching things together makes it easy for that granularity/control to be lost. Single-item transactions also make it possible to detach listeners as needed – whereas with a batched assignment, it'd require more overhead to search for & remove the single item.

function setState(state, prevState) {
  // ...
}

store.listen('event1', setState);
store.listen('event2', setState);

If you're determined to batch-assign, you can make your own helper:

function batch(store, events, func) {
  let unlisten = events.map(x => store.listen(x, func));
  return () => unlisten.forEach(x => x());
}

let removeAppStoreListeners = batch(mystore, ['event1', 'event2'], setState);
if (...) removeAppStoreListeners();

Hope that helps~!