-->

Message boxes in Polymer applications

2019-08-21 11:19发布

问题:

I am working on my first bigger Polymer application and currently have around 30 components. Most of the components need to be able to display (modal) message boxes. For this I implemented a message box component wrapping paper-dialog (similar to other message box components available).

What I don't like is that in every component which wants to display message boxes I need to define an element

<my-message-box id="message-box"></my-message-box>

and then call it like this

this.$["message-box"].information("Something happened...");

This works but my gut feeling is that a message box should be more like a global service, a singleton maybe. In C# f.e. there exists a static method on the MessageBox class.

Is the above mechanism really the recommended way to do it or are there better solutions to it?

回答1:

My current approach is to create error-dialog and add it as a sibling to my main-app in index.html:

<body>
  <main-app></main-app>
  <error-dialog></error-dialog>
  <noscript>
    Please enable JavaScript to view this website.
  </noscript>
</body>

error-dialog's ready() method adds a custom event:

ready() {
  super.ready();
  this.addEventListener('o_error', e => this._errorListener(e));
}

_errorListener(e) {
  this.o_error = e.detail;
  this.$.errorDlog.open();
}

Now I can open error-dialog from anywhere with

let msg = ...
const dlog = document.querySelector('error-dialog');
dlog.dispatchEvent(new CustomEvent('o_error', {detail: msg, bubbles: true, composed: true}));