Reputation: 49
I have a dice game and there is a function rollDice() for dice rolling and it will trigger a custom event rollDice on document every time it is called.
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: { value: Math.floor(Math.random() * 6) + 1 },
bubbles: true,
cancelable: false
})
);
};
I have a button that listens the click event and calls the rollDice() function on every click
<button id="roll-button"><span class="dice">⚂</span></button>
var element = document.getElementById('roll-button');
element.addEventListener('click', rollDice);
I should listen to the custom 'rollDice' event triggered on the document whenever the rollDice() function is called. Inspect the triggered event and pick up the current value of the roll (detail.value). I'm not just sure how to use the click event and the custom event together to get the dice value everytime the button is clicked.
Upvotes: 0
Views: 855
Reputation: 207511
Add an event listener for your custom event.
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: { value: Math.floor(Math.random() * 6) + 1 },
bubbles: true,
cancelable: false
})
);
};
document.addEventListener('rollDice', function (evt) {
console.log(evt.detail.value);
});
var element = document.getElementById('roll-button');
element.addEventListener('click', rollDice);
<button id="roll-button"><span class="dice">⚂</span></button>
In the end, not sure why a custom event would be needed. Seems like calling a function would be easier.
Upvotes: 2