base.Dispatcher(…eventTypes)

Simple dispatcher (event bus).

It takes a fixed list of event types upon construction. Attempts to use an unknown event will throw an error.

One approach is to define both present and past tense events so that handlers can prepare for and react to events.

new Dispatcher(…eventTypes)

Parameters:
Name Type Attributes Description
eventTypes module:base.Dispatcher~EventType <repeatable>

Event types this instance can handle.

Example
const events = [
  // @event module:lib.Klass#run
  'run',
  // @event module:lib.Klass#ran
  'ran',
  // @event module:lib.Klass#jump
  'jump',
  // @event module:lib.Klass#jumped
  'jumped',
  // @event module:lib.Klass#duck
  'duck',
  // @event module:lib.Klass#ducked
  'ducked',
];

function handleRunJump(evt, data) {
  switch (evt) {
    case 'run':
    case 'jump':
      // ...
      break;
    case 'ran':
      // ...
      break;
    case 'jumped':
      // ...
      break;
}

function handleDuck(evt, data) {
  // ...
}

function handleDucked(evt, data) {
  // ...
}

 const dispatcher = new Dispatcher(...events);

 dispatcher.on('run', handleRunJump)
  .on('ran', handleRunJump)
  .on('jump', handleRunJump)
  .on('jumped', handleRunJump)
  .on('duck', handleDuck)
  .on('ducked', handleDucked);

 dispatcher.fire('jump', jumpData)
   .fire('duck', duckData);
 // ... more stuff ...
 dispatcher.fire('jumped', jumpData)
   .fire('ducked', duckData);

Members

enabled :boolean

Methods

fire(eventType, data) → {module:base.Dispatcher}

Calls all registered functions for the given eventType.

Parameters:
Name Type Description
eventType module:base.Dispatcher~EventType

Event type to use.

data object

Data to pass to each function.

Returns:
module:base.Dispatcher -

This instance, for chaining.

off(eventType, func) → {module:base.Dispatcher}

Remove all instances of a function registered to an eventType.

Parameters:
Name Type Description
eventType module:base.Dispatcher~EventType

Event type to disconnect from.

func module:base.Dispatcher~Handler

Function to remove.

Returns:
module:base.Dispatcher -

This instance, for chaining.

on(eventType, func) → {module:base.Dispatcher}

Attach a function to an eventType.

Parameters:
Name Type Description
eventType module:base.Dispatcher~EventType

Event type to connect with.

func module:base.Dispatcher~Handler

Single argument function to call.

Returns:
module:base.Dispatcher -

This instance, for chaining.

Type Definitions

EventType

Handler(eventType, data)

Parameters:
Name Type Description
eventType module:base.Dispatcher~EventType

Event type.

data object

Event data.