BBC's guide to development
  • General

    • About
    • Tools
    • Git(hub)
    • Showpad
    • Hosting
    • Maintenance
    • Security
    • Go live checklist
  • Front-end development

    • Bundlers
    • CSS/SCSS
    • Javascript
    • Vue
    • PHP
    • Mails
    • Dev Faq
  • Functions
  • Mixins
  • General

    • OOP Structure
  • Component Classes

    • Accordion
    • App
    • Component
    • HighwayApp
    • Popup
    • PNG Sequencer
    • Tab
  • Manager Classes

    • BountListenerMgr
    • Cache
    • Configuration
    • InViewStateMgr
    • Instance Manager
    • Event dispatcher
  • Factories

    • SwiperFactory
  • PDF

    • AssetLoader
    • BasePdfDoc
    • TemplatePdfDoc
    • CustomPdfDoc
  • Utility functions

    • canvas
    • Connection Status
    • css
    • dev
    • placeholder
    • dom
    • fetch
    • json
    • object
    • scroll
    • scrollbar
    • spreadsheets
    • string
    • url
  • General

    • ComponentMgr
    • ThreeJsViewer
  • Components

    • ComponentMgr
    • GltfModel
    • Snappable
    • Socket
    • ThreeJsViewer
    • ThreeJsViewerCamera
  • Loaders

    • ConfigurationSerializer
    • GltfBlockParser
  • Utils

    • CanvasInputAdapter
    • CollisionManager
    • SocketGridExpander
    • blender
    • headless
  • General

    • Troubleshooting
    • Legacy
  • Components

    • AssetBar
    • ConfigGenerator
    • ShowpadApp
  • Managers

    • Assets
    • AppsDb
    • Config
  • Utils

    • Connection Status
    • general
    • showpad-interactive
    • showpad-upload
  • Components

    • Accordion
    • BackButton
    • Breadcrumb
    • ByltButton
    • Hamburger
    • Icon
    • Logo
    • Loader
    • Modal
    • Popup
    • Prompt
    • ProgressBar
    • TextLoader
  • Composables

    • useDebugMode
    • useConnectionStatus
  • Utils

    • dom
    • props
  • General

    • General
    • Tracking
  • Components

    • Accordion
    • ActionButton
    • AssetItem
    • AssetList
    • BackButton
    • ConfigGenButton
    • Logo
    • Media
    • Modal
    • Popup
    • Prompt
    • SPButton
    • SPRouterView
    • SPTrackedRouterLink
    • TextLoader
    • View
  • Composables

    • useConnectionStatus
  • Stores

    • useAppsDbStore
    • useBreadcrumbStore
    • useShowpadAPIStore
    • useShowpadSDKStore
    • useSpConfigStore
    • useSpStore
    • useSpTrackingStore
  • The New Kit

    • General
    • Installation & Usage
    • ACF Blocks
    • PHPCS
    • Functions
    • Vite
    • WP Config
    • Staging Deployment
  • Best Practices

    • Page Structure
    • Fonts/Typography
  • Todo
GitHub
  • General

    • About
    • Tools
    • Git(hub)
    • Showpad
    • Hosting
    • Maintenance
    • Security
    • Go live checklist
  • Front-end development

    • Bundlers
    • CSS/SCSS
    • Javascript
    • Vue
    • PHP
    • Mails
    • Dev Faq
  • Functions
  • Mixins
  • General

    • OOP Structure
  • Component Classes

    • Accordion
    • App
    • Component
    • HighwayApp
    • Popup
    • PNG Sequencer
    • Tab
  • Manager Classes

    • BountListenerMgr
    • Cache
    • Configuration
    • InViewStateMgr
    • Instance Manager
    • Event dispatcher
  • Factories

    • SwiperFactory
  • PDF

    • AssetLoader
    • BasePdfDoc
    • TemplatePdfDoc
    • CustomPdfDoc
  • Utility functions

    • canvas
    • Connection Status
    • css
    • dev
    • placeholder
    • dom
    • fetch
    • json
    • object
    • scroll
    • scrollbar
    • spreadsheets
    • string
    • url
  • General

    • ComponentMgr
    • ThreeJsViewer
  • Components

    • ComponentMgr
    • GltfModel
    • Snappable
    • Socket
    • ThreeJsViewer
    • ThreeJsViewerCamera
  • Loaders

    • ConfigurationSerializer
    • GltfBlockParser
  • Utils

    • CanvasInputAdapter
    • CollisionManager
    • SocketGridExpander
    • blender
    • headless
  • General

    • Troubleshooting
    • Legacy
  • Components

    • AssetBar
    • ConfigGenerator
    • ShowpadApp
  • Managers

    • Assets
    • AppsDb
    • Config
  • Utils

    • Connection Status
    • general
    • showpad-interactive
    • showpad-upload
  • Components

    • Accordion
    • BackButton
    • Breadcrumb
    • ByltButton
    • Hamburger
    • Icon
    • Logo
    • Loader
    • Modal
    • Popup
    • Prompt
    • ProgressBar
    • TextLoader
  • Composables

    • useDebugMode
    • useConnectionStatus
  • Utils

    • dom
    • props
  • General

    • General
    • Tracking
  • Components

    • Accordion
    • ActionButton
    • AssetItem
    • AssetList
    • BackButton
    • ConfigGenButton
    • Logo
    • Media
    • Modal
    • Popup
    • Prompt
    • SPButton
    • SPRouterView
    • SPTrackedRouterLink
    • TextLoader
    • View
  • Composables

    • useConnectionStatus
  • Stores

    • useAppsDbStore
    • useBreadcrumbStore
    • useShowpadAPIStore
    • useShowpadSDKStore
    • useSpConfigStore
    • useSpStore
    • useSpTrackingStore
  • The New Kit

    • General
    • Installation & Usage
    • ACF Blocks
    • PHPCS
    • Functions
    • Vite
    • WP Config
    • Staging Deployment
  • Best Practices

    • Page Structure
    • Fonts/Typography
  • Todo
GitHub
  • EventDispatcher Class

EventDispatcher Class

import EventDispatcher from '@bbc/front-end-kit/js/managers/EventDispatcher';

Summary

The EventDispatcher class extends EventTarget to provide a simple and robust way of adding, removing, and managing event listeners for you custom classes

Introduction

The EventDispatcher class provides an easy-to-use interface for managing event listeners. It extends the built-in EventTarget class to provide additional functionality such as tracking the listeners added, and enabling/disabling all event dispatching on the instance.

Tips

This class also contains a BoundListenerMgr class that is used to manage the listeners added to the instance. Which is very handy when extending the and managing events inside the child class.

Check the BoundListenerMgr class for more information.

Getting Started

To get started, you can create an instance of the EventDispatcher class and start adding listeners to it using the addEventListener or on methods:

const dispatcher =  new  EventDispatcher();

// Adding an event listener
dispatcher.addEventListener('click',  (event)  =>  {
	console.log('Clicked!', event);
});

// Using on() method to add event listener
dispatcher.on('custom',  (event)  =>  {
	console.log('Custom event!', event);
});

// Extends your custom class easily
import EventDispatcher from  'path/to/EventDispatcher';

// custom class extending EventDispatcher so it can
class  CustomClass  extends  EventDispatcher  {
	constructor()  {
		super();
	}
	
	customMethod()  {
		this.dispatchEvent('customEvent');
	}
}

// initiate CustomClass
const emitter =  new CustomClass();

// add evemt listener to customEvent
emitter.addEventListener('customEvent',  (event)  =>  {
	console.log('Event received!', event);
});

// custom method will dispatch customEvent which will be caught by the listener loggin 'Event received!'
emitter.customMethod();

Pass data to listener when dispatching

When the event parameter is a string/key, the options parameter is passed to the automatically constructed CustomEvent. This provides support for all the parameters Event and CustomEvent provide in conjonction with Event Target, like the detail option.

Using the detail property it is possible to pass values alongside the event from the scope the event is dispatched from to the scope the listener is running in.

instance.on('custom-event', (e) => {
	console.log(e.detail.value) // logs: 'true' in the console
})

instance.dispatchEvent('custom-event', { 
	detail: {
		value: true
	}
});

Tips

Avoid passing datatypes (int, string, ...) or instances of classes directly to the detail property. Wrap it in an object with properties to keep expectations and flexibility of the codebase to a maximum.

❎ NO

instance.dispatchEvent('custom-event', { 
	detail: 255
});

✅ YES

instance.dispatchEvent('custom-event', { 
	detail: {
		count: 255
	}
});

Run listener once

With the option parameter of .addEventListener it is also possible to tell the Event Target to instantly remove the eventlistener after the listenener has finished running.

instance.on('custom-event', (e) => {
	console.log('custom-event fired!') 
}, { once: true })

// fire first time (logs 'custom-event fired!' in the console)
instance.dispatchEvent('custom-event'); 

// fire second time (does not log anything in the console)
instance.dispatchEvent('custom-event');

Silence the instance

It is possible to silence the listener so logic that would dispatch events can be silenced. This is usefull to supress events of tasks for a while.

const instance = new EventDispatcher();

// set listener
instance.on('my-event', () => console.log('my-event dispatched'));

// will dispatch event
instance.dispatchEvent('my-event');

// will not dispatch events when called
instance.isSilent = true
instance.dispatchEvent('my-event');

// will dispatch events again
instance.isSilent = false
instance.dispatchEvent('my-event');

Integrated BoundListenerMgr

The EventDispatcher class contains a BoundListenerMgr class that is used to manage the listeners added to the instance. Which is very handy when extending the and managing events inside the child class.

Check the BoundListenerMgr class for more information.

How it works

When adding a listener to the EventDispatcher instance, the BoundListenerMgr class is used to store the listener and the event type. A key is generated to track the bound listener to the right event by combining the event type and a string version of the given listener function.

This key is regenerated when the listener is removed to clean up the map of bound listeners.

API

constructor(...args)

The constructor method initialises a new EventDispatcher instance.

Parameters

  • ...args: A list of arguments to pass to the EventTarget constructor.

Return

Returns undefined.

Methods

addEventListener(type, listener, options)

Adds an event listener to the EventDispatcher.

Parameters
  • type: A string representing the event type to listen for.
  • listener: A function to be called when the event is dispatched.
  • options (optional): An object that specifies characteristics about the event listener. (more info). Supports one extra property beyond the standard:
    • scope: When provided, the listener is auto-bound to this scope via the internal BoundListenerMgr. The scope key is stripped before being forwarded to EventTarget.
Return

Returns undefined.

removeEventListener(type, listener, options)

Removes an event listener from the EventDispatcher.

Parameters
  • type: A string representing the event type to remove the listener from.
  • listener: The listener function to remove.
  • options (optional): An object that specifies characteristics about the event listener. (more info)
Return

Returns undefined.

on(...args)

An alias for the addEventListener() method.

Return

Returns undefined.

Parameters
  • ...args: A list of arguments to pass to the addEventListener() method.
Return

Returns undefined.

off(...args)

An alias for the removeEventListener() method.

Parameters
  • ...args: A list of arguments to pass to the removeEventListener() method.
Return

Returns undefined.

getListeners(type)

Returns the listeners tracked for a given event type, or the full listener map when no type is given.

Parameters
  • type (optional): A string representing the event type to retrieve the listeners for.
Return
  • When type is provided: Set<{ listener, options, useCapture }> for that event type, or undefined if none.
  • When type is omitted: the full internal Map<string, Set> of all tracked listeners.

hasListeners(type)

Returns true if there are any listeners for a specific event type.

Parameters
  • type (optional): A string representing the event type to check for listeners.
Return

Boolean

dispatchEvent(event, options)

Dispatches an event with the EventDispatcher.

Parameters
  • event: An Event object to dispatch or a string representing the event type to create a new CustomEvent.
  • options (optional): An object that specifies characteristics about the CustomEvent in case the given event parameter is a String.
Return

Returns undefined.

destroy()

Removes all event listeners from the EventDispatcher instance and clears any internal state.

Return

Returns undefined.

toString()

Returns a string representing the EventDispatcher class.

Getters & Setters

isSilent

Flag to silence the dispatchEvent method. Set to true to block all event dispatching on this instance.

listeners

The internal Map<string, Set> of all tracked listeners, keyed by event type.

blm

The internal BoundListenerMgr instance used to manage auto-bound listeners added via options.scope.

Private properties

_isSilent

Flag to silence the dispatchEvent method. Set to true to block event dispatchment.

_listeners

Map of containing all listeners coupled to event keys.

Edit this page
Last Updated: 4/27/26, 12:56 PM
Contributors: Nicolas Jaenen