commandBus.on¶
The on
method allows to listen to the command similarly to how addEventListener
works for DOM events.
Input parameters¶
messageName¶
messageName
is a mandatory parameter of the string
type which represents the name of the message to listen to.
listener¶
listener
is a mandatory parameter of type TMessageListener which represents a callback for the command emission.
Example¶
To listen to any command emitted by the Command Bus you can use the on
method:
useStorefront(async (storefront) => {
storefront.commandBus.on('example-command', () => {
console.log('Listening to the command...')
});
});
Example¶
Remember that the command bus does not allow two listeners:
useStorefront(async (storefront) => {
storefront.commandBus.on('example-command', () => {
console.log('Listening to the command...')
});
storefront.commandBus.on('example-command', () => { // Error: Maximum number of listeners reached
console.log('Listening to the command for the second time...')
});
});
Listening with on
and once at the same time is also not allowed:
useStorefront(async (storefront) => {
storefront.commandBus.once('example-command', () => {
console.log('Listening to the command...')
});
storefront.commandBus.on('example-command', () => { // Error: Maximum number of listeners reached
console.log('Listening to the command with on...')
});
});