Search code examples
javascriptmodel-view-controllerpolymerdom-events

Lateral communication in Polymer


Here is the problem:

Any two Polymer elements may need to communicate. No assumption is made as to where these elements might be in the DOM (or shadow DOM), this means one event cannot simply bubble up to another element.

The good old way to achieve this would have been to let events bubble up to the root node and then fire broadcast events on the root node for other elements to listen to.

This approach however breaks encapsulation and seems to go against Polymer's overall design. AngularJS for example provides an event broadcaster that keeps controllers from unnecessarily keeping references to the root node.

Can such approach be achieved with Polymer? Otherwise can this be solved with a different approach?


Solution

  • You should be able to do this using polymer-signals

    http://www.polymer-project.org/articles/communication.html#using-ltpolymer-signalsgt

    Quoting from the doc:

    Your element fires polymer-signal and names the signal in its payload:

    this.fire('polymer-signal', {name: "foo", data: "Foo!"});
    

    This event bubbles up to document where a handler constructs and dispatches a new event, polymer-signal-foo, to all instances of . Parts of your app or other Polymer elements can declare a element to catch the named signal:

    <polymer-signals on-polymer-signal-foo="{{fooSignal}}"></polymer-signals>