Search code examples
javascripthtmldata-bindingpolymerweb-component

With regards to Polymer, How do I get one web component to 'speak' to another web component?


I want to be able to fill out a form in web component 1, click a submit button in web component 1 and then post that data to a grid in web component 2. Web component 1 is in a different html file then web component 2.

//web component 1
<dom module id="foo-form">
<template>
  <paper-input id="myID" label="ID"value="{{myID}}"></paper-input>
  <paper-button id="submitForm" on-click="submitForm">Submit</paper-button>
</template>
 <script>
  (function() {
    "use strict";
  Polymer({
    is: 'foo-form',
     });
    })();
 </script>
</dom-module>


//Web component 2*
<dom-module id="my-grid">
  <template>
    <vaadin-grid selection-mode="single" id="fooBarGrid" >
      <table>
        <col name="vendorID" sortable="" />
        <thead>
          <tr>
            <th>ID</th>
         </tr>
        </thead>
      </table>
    </vaadin-grid>
  </template>
 <script>
   document.addEventListener("WebComponentsReady", function() {

      // Reference to the grid element.
      var grid = grid || document.querySelector("#fooBarGrid");

      // Reference to the template element
      var template = template || document.querySelector("template");

      // Add some example data as an array.
      var data = [
        { "myId": 0 } 
      ];
      grid.items = data;
 });

  </script>
 <script>
    (function() {
      'use strict';

      Polymer({
          is: 'my-grid',
        });
    })();
  </script>
</dom-module>

Solution

  • There are basically two ways to do it:

    1. Use the mediator pattern. This works well if you have a parent element that contains both your my-grid and foo-form element. A solution can be found here
    2. If you want to communicate between elements that don't have a common parent or different DOM branches, you can use iron-signals which provies basic publish and subscribe functionality.

    Solution 1 is the recommended approach.