Reputation: 101
I have a button with a 'click' event listener, this event is made in 'example1.js', I need to create another event lister in 'example2.js' but the logic in this listener depends on what is returned from the first one.
example1.js:
button.addEventListener('click', () => {
const confirmation = confirm('Are you sure you want to do that?');
<some code here>
});
example2.js:
button.addEventListener('click', () => {
if (<confirmation from 1st listener>) {
do some stuff here...
}
});
I am aware of custom events:
const confirmationResponse = new CustomEvent('customEventListener', {detail: {isConfirm: confirmation}});
button.addEventListener('customEventListener', (event) => {
console.log(event.detail)
});
button.dispatchEvent(confirmationResponse);
I am not sure how to implement the logic between the two files since all tutorials I found are in one file, which would make the variable accessible.
Upvotes: 0
Views: 1296
Reputation: 184
But before doing that, I would consider why you're in need to do that. If those buttons are in the same form, component, etc., they probably should sit in one class/file/etc. (my opinion)
EDIT: btw referring to title, you're not listening to another event, but reading a variable changed in another event :P
Upvotes: 0