Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does data-binding in Polymer work?

Tags:

polymer

<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="new-tag">
    <template>
        <input id="input" value="{{value}}" type="text" />
    </template>
    <script>
        (function () {
            Polymer("new-tag", {
                value: ""
            });
        })();
    </script>
</polymer-element>

If I change the value property of the DOM object (in JS) I can see that the text field's value changes. If I change the text field value, the DOM object property value also changes.

But both these changes don't affect the value attribute.

If the value attribute doesn't change, how is the change in model, reflecting in the view?

I was thinking that value={{value}} is a way of saying "when the value property changes, change the value attribute and vice versa". But if value attribute is not being the link between the view and the model, how are the changes being propagated?

Also, what exactly does value={{value}} mean?

like image 852
batman Avatar asked May 25 '14 23:05

batman


2 Answers

Reflecting property values back to the attribute is now opt-in. The docs are in the process of being updated to reflect this. To get this behavior, instead of using the attributes attribute on your polymer-element tag, use the publish property in your call to Polymer(), like so:

Polymer({
  publish: {
    // won't reflect to an attribute
    bigText: '',
    // will reflect to an attribute
    active: {value: false, reflect: true}
  },
  ...
)};
like image 196
CletusW Avatar answered Oct 21 '22 13:10

CletusW


In Polymer 1.0 there is the two ways data binding for native elements or in general non-Polymer elements. You need to specify the event ::input as in the following instruction:

 <input id="input" value="{{modelvalue::input}}" type="text" />

Anytime the user types something in the text box, the modelvalue property is updated. Hence, element attribute value and property value are in sync.

Code snippet

The following is a complete working and running example:

<base href="http://polygit.org/components/">
<link href="polymer/polymer.html" rel="import">

<dom-module is="new-wc">
    <template>
       
      <input id="input" value="{{modelvalue::input}}" type="text" />
      
      <p>
        Default value is <span>{{modelvalue}}</span>  
      </p>
      
    </template>
    <script>
      Polymer({
         is: "new-wc",

         properties: {
            modelvalue: { type: String, value: "0" }
         }
      });
    </script>
</dom-module>

<p><b>Code snippet description: </b>this polymer code snippet demonstrates how to use the two ways binding for native or non-polymer elements. Just type something within the text box and you will see the typed text updated below.</p>
  
<new-wc></new-wc>
like image 4
Donato Pirozzi Avatar answered Oct 21 '22 12:10

Donato Pirozzi