Share Data between Riot Components with Mitt (event emitter)

Example of dialog component made with RiotJS to emit Event to a listener.

<c-dialog> <dialog class=" {state.active ? 'active ' : null} {props?.blur ? 'overlay blur ' : null} {props?.left ? 'left ' : null} {props?.right ? 'right ' : null} {props?.top ? 'top ' : null} {props?.bottom ? 'bottom ' : null} {props?.max ? 'max ' : null} " > <h5>{ state.title }</h5> <div> { state.message } </div> <nav class="right-align no-space"> <button onclick={ toggleModal } class="transparent link">{ state.cancel }</button> <button onclick={ (ev) => clicked(ev, "confirm") } class="transparent link">{ state.validate }</button> </nav> </dialog> <script> import events from './events.js' export default { state: { active: false, title: 'Confirmation', message: 'Are you sure?', callbackID : '', args : true, validate : 'Validate', cancel: "Cancel" }, onMounted() { console.log("EVENTS LISTENING"); events.on('open-modal-validation', this.openModalValidation); }, onUnmounted() { events.off('open-modal-validation', this.openModalValidation); }, validateAction () { if (this.state.callbackID) { events.emit(this.state.callbackID, this?.state?.args); } this.toggleModal(); }, openModalValidation ({ message, callbackID, args }) { this.update({ active: true, message, callbackID, args: args ?? true }) }, toggleModal() { this.update({ active: !this.state.active }) if (this.state.active === false) { this.update({ message: '', busID: '', args: true }) } } } </script>
</c-dialog>
Enter fullscreen mode
Exit fullscreen mode
<index-riot> <div style="width:600px;padding:20px;"> <c-dialog /> <c-button onclick={ confirmDeletion }> Delete File </c-button> </div> <script> import cButton from "../../components/c-button.riot"; import cSnackbar from "../../components/c-snackbar.riot"; import cDialog from "./c-dialog.riot"; import events from "./events.js" export default { components: { cButton, cDialog }, onMounted() { events.on('delete-file', this.deleteFile); }, onUnmounted() { events.off('delete-file', this.deleteFile); }, state: { active: false }, confirmDeletion () { events.emit('open-modal-validation', { message: "Do you confirm you want to delete the file \"2024-04-invoice.pdf\"?", callbackID: 'delete-file' }); }, deleteFile () { console.log("FILE DELETED! 🗑️"); } } </script>
</index-riot>
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
The “version” in docker compose file. Privacy, cookie & data policy.