polymerpolymer-2.x

Iron-signal alternate in Polymer 2?


I have been using iron-signals almost everywhere in my application.

Now I was upgrading my polymer 1 application to polymer 2 and I found that <iron-signals> is not used anymore.

What is the alternate path to achieve the same. I basically want to pass data between different pages in my web app.


Solution

  • You should be able to simply dispatch events on window from one element and listen for them in other elements.

    Example:

    // Element 1
    
    class FooElement extends Polymer.Element {
      connectedCallback() {
        super.connectedCallback()
      }
    
      ready() {
        super.ready()
        window.addEventListener('bar-was-called', e => {
          console.log(e.detail) // logs 'hello-bar'
        })
      }
    }
    
    // Element 2
    
    class BarElement extends Polymer.Element {
      connectedCallback() {
        super.connectedCallback()
      }
    
      ready() {
        super.ready()
      }
    
      doBar() {
        window.dispatchEvent(new CustomEvent('bar-was-called', { 
          detail: 'hello-bar' 
        }))
      }
    }
    

    Side note

    Keep in mind that iron-signals was removed for a reason. AFAIK it's that it promotes a hard-to-debug communications architecture.

    From <iron-signals> README:

    Note: avoid using iron-signals whenever you can use a controller (parent element) to mediate communication instead.