Skip to content

Commit

Permalink
Dispatch an event to a modal being closed before closing it, so that …
Browse files Browse the repository at this point in the history
…the modal can prevent it based on its state (#466)
  • Loading branch information
osmianski authored Oct 7, 2024
1 parent 277c6c8 commit 77ee949
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,29 @@ By default, the modal will close when you click outside the modal. If you want t
}
```

## Preventing closing the modal on Escape or on click away based on the modal state

When a modal is closed on Escape or click away, `closingModalOnEscape` and `closingModalOnClickAway` are issued. Handle these events to prevent closing a modal based on its state, for example, if there are uncommitted changes.

For example, if a modal has a `isDirty` property, it could have the following handler:

```
@script
<script>
$wire.on('closingModalOnEscape', data => {
if ($wire.isDirty && !confirm('{{ __('You have unsaved changes. Are you sure you want to close this dialog?') }}')) {
data.closing = false;
}
});
$wire.on('closingModalOnClickAway', data => {
if ($wire.isDirty && !confirm('{{ __('You have unsaved changes. Are you sure you want to close this dialog?') }}')) {
data.closing = false;
}
});
</script>
@endscript
```

## Skipping previous modals
In some cases you might want to skip previous modals. For example:
1. Team overview modal
Expand Down
20 changes: 20 additions & 0 deletions resources/js/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ window.LivewireUIModal = () => {
return;
}

if (!this.closingModal('closingModalOnEscape')) {
return;
}

let force = this.getActiveComponentModalAttribute('closeOnEscapeIsForceful') === true;
this.closeModal(force);
},
Expand All @@ -24,8 +28,24 @@ window.LivewireUIModal = () => {
return;
}

if (!this.closingModal('closingModalOnClickAway')) {
return;
}

this.closeModal(true);
},
closingModal(eventName) {
const componentName = this.$wire.get('components')[this.activeComponent].name;

var params = {
id: this.activeComponent,
closing: true,
};

Livewire.dispatchTo(componentName, eventName, params);

return params.closing;
},
closeModal(force = false, skipPreviousModals = 0, destroySkipped = false) {
if(this.show === false) {
return;
Expand Down

0 comments on commit 77ee949

Please sign in to comment.