Search code examples
javascriptpolymerweb-componentpaper-elements

Synchronize values of two paper-inputs on change event


I have a polymer paper-input element on HTML page (among other webcomponents). I need to listen on it’s value change and modify another webcomponent’s property. For a sake of simplicity, let’s imagine I need two syncronized inputs. So far, I have:

<paper-input id="fst" label="First" floatinglabel="First"></paper-input>
<paper-input id="snd" label="Second" floatinglabel="Second"></paper-input> 

I want to have their values to be synchronized all the way. Currently I use following code to achieve this:

document.addEventListener('polymer-ready', function() {
  ['#fst', '#snd'].forEach(function(el) {
    document.querySelector(el).addEventListener("change", function(e) {
      var value = document.querySelector(el).value;
      //                     ⇓⇓⇓⇓⇓⇓⇓ in pseudocode: other element
      document.querySelector(XOR(el)).setAttribute('value', value);
    });
  });
  ...
});

I definitely see this is ugly. I am sure, there is a proper way to achieve the goal, but I failed to google it and I’m totally stuck. I suppose observes should do the trick, but I simply can’t figure out how.

The evident code using binding variable is not working for some reason:

<paper-input id="fst" label="First" floatinglabel="First" value="{{ value }}">
</paper-input>
<paper-input id="snd" label="Second" floatinglabel="Second" value="{{ value }}">
</paper-input> 

Thanks in advance.


Solution

  • you could use the declarative method and just use something like

    <template is="auto-binding">
      <paper-input id="fst" label="First" floatinglabel="First" value="{{value}}"></paper-input>
      <paper-input id="snd" label="Second" floatinglabel="Second" value="{{value}}"></paper-input>    
    </template>
    

    plunker shows it in action

    http://plnkr.co/edit/3cxdOYKciKRBzROHQzgM?p=preview

    edit: update answer to reflect that the use of declarative binding outside a custom element requires a auto-binding template. also it is worth noting that elements inside the auto-binding template are not accessible until the template-bound event is fired.