danielvdende
danielvdende

Reputation: 710

Pass data to another Polymer component

I am working on a dashboard, in which I have a search panel at the top (let's call it component A), where users can enter a query. The value of this input will change a lot of other components in the dashboard (not only components that are its direct descendants or siblings). I want to send the search value from component A to component B, which should then respond by performing some action with the input value.

I have tried a few things:

  1. Directly calling the function in component B. Haven't been able to get that to work at all.
  2. Manually setting B's local property value and using an observer to trigger a function call. I manager to set the value, but the observer does not trigger.
  3. Using a global variable, which I can easily access across components, but I still can't trigger functions in specific components.

How can I best do this? I'm relatively new to Polymer, so forgive me if my ideas aren't completely 'Polymerised' :)

Approach 1

<dom-module id="component-B">
  <template>
  </template>
  <script>
    Polymer({
      is: 'component-B',
      properties: {
        id: '',
        observer: '_idUpdate'
      },
      _idUpdate: function(){
        console.log("HELLO");
      }
    });
  </script>
</dom-module>

<dom-module id="component-A">
  <template>
  </template>
  <script>
    Polymer({
      is: 'component-A',
      idSearch: function() {
        var id = this.$.search.value;
        document.querySelector('component-B').properties.id = id;
      },
    });
  </script>
</dom-module>

Upvotes: 1

Views: 1626

Answers (1)

a1626
a1626

Reputation: 2964

As you want to send data to multiple elements (which might not be siblings of the firing element) you can use any of these two methods

  • Use iron-signal to fire the signal and then in all the elements where you want the data use iron-signal tag to listen to the signal

     <iron-signals on-iron-signal-<signal-name>="<function>"></iron-signals>
    
  • You can also use standard HTML method dispatchEvent to fire a signal and then add eventListeners in all the element where you want data.

Upvotes: 1

Related Questions