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 theEventTargetconstructor.
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 internalBoundListenerMgr. Thescopekey is stripped before being forwarded toEventTarget.
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 theaddEventListener()method.
Return
Returns undefined.
off(...args)
An alias for the removeEventListener() method.
Parameters
...args: A list of arguments to pass to theremoveEventListener()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
typeis provided:Set<{ listener, options, useCapture }>for that event type, orundefinedif none. - When
typeis omitted: the full internalMap<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: AnEventobject to dispatch or a string representing the event type to create a newCustomEvent.options(optional): An object that specifies characteristics about theCustomEventin 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.