This page is part of a static HTML representation of TriTarget.org at https://tritarget.org

ModalManager

Sukima1st November 2022 at 9:32pm

I coined this term an OOP design pattern. The idea is that it covers the behavior of opening and closing a modal dialog by means of an .open() method which returns a promise that resolves to a Tuple that informs how the modal was dismissed. It also offers some methods for dismissing the modal which the dialog code can use as the manager can be passed to the dialog code.

The simplest version of this might look like:

class ModalManager {
  #resolve = () => {};
  #reject = () => {};
  isOpen = false;
  open() {
    return new Promise((resolve, reject) => {
      this.#resolve = resolve;
      this.#reject = reject;
      this.isOpen = true;
    }).finally(() => (this.isOpen = false));
  }
  cancel() {
    this.#resolve({ reason: 'cancelled' });
  }
  confirm(value) {
    this.#resolve({ reason: 'confirmed', value });
  }
  reject(value) {
    this.#resolve({ reason: 'confirmed', value });
  }
  error(error) {
    this.#reject(error);
  }
}

For a production ready version I have a micro-lib: