r/JavaFX • • Dec 04 '24

Discussion Dialogs in MVVM

There was recently a post how to display dialogs in MVCI. But what about dialogs in MVVM? It's actually not a simple question. For example, I decided to use dialog service, that knows and uses view:

in View:

viewModel.setDialogService(new DialogServiceImpl(this));

In ViewModel:

var result = this.dialogService.openSomeDialog(someDialogVM);

For example, we have a dialog that consists of AlertView and AlertViewModel. Now FooViewModel wants to show this dialog. FooViewModel knows only AlertViewModel but it doesn't know AlertView. So, we create a DialogService that is available in FooViewModel, something like

public interface FooDialogService extends DialogService {
    void openAlertDialog(AlertViewModel dialogVM);
}

and after that in FooViewModel

this.dialogService.openAlertDialog(alertVM)

So, FooDialogService knows FooView and AlertView and has instance of AlertViewModel.

And what solution do you use?

3 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Dec 04 '24 edited Dec 04 '24

You have presumably created a MVVM construct for your Alert, and you are connecting it to your client MVVM constructs through the ViewModels.

Yes, that's right.

I probably wouldn't bother with the MVVM structure to implement it.

Yes, we thought about it, but decided to use same approach for simple and complex dialogs, popup windows etc. Because sometimes you create a very simple dialog, that later it can become more complex. So, we decided to make everything MVVM. Besides, it is easy to remember :)

What about showAndWait. There are two variants - the first one is like you described. The second one is simpler:

class AlertViewModel {
   private final ObjectProperty<Runnable> okAction = new SimpleObjectProperty();

   public ObjectProperty<Runnable> okActionProperty() {
      return this.okAction;
   }
   ...
}

class AlertView {
   private final Button okButton = new Button("Ok");

   AlertView(AlertViewModel vm) {
     this.okButton.onActionProperty().set(e -> vm.okActionProperty().get().run());
   }
   ...
}

So, in this variant we don't get Result, but we work directly with actions. In FooViewModel:

var alert = new AlertViewModel("Hey, there! Don't do that!");
alert.okActionProperty().set(....);
this.dialogService.openAlertDialog(alert);