-->

Polymer 1.0: Two-way data binding: to/from

2019-07-10 11:12发布

问题:

I want to two-way databind the field values of an iron-form to a Firebase node (representing user-defined settings, for example).

settings.html
<dom-module id="my-settings">
  <template>
    <firebase-document location="[[firebaseUrl]]"
                       data="{{form}}">
    </firebase-document>
    <form is="iron-form" id="form">
      <paper-checkbox id="history"
                      name="history"
                      on-change="_computeForm"
                      >Save history
      </paper-checkbox>
      <!-- ... -->
      <!-- All types of form fields go here -->
      <!-- ... -->
    </form>
  </template>
  <script>
    (function() {
      Polymer({
        is: 'my-settings',
        _computeForm: function() {
          this.form = this.$.form.serialize();
        }
      });
    })();
  </script>
</dom-module>

This form needs to:

  • persist its state to firebase upon changes (i.e., first-way binding — client to firebase) and
  • set form fields to their saved values upon loading (i.e., second-way binding — firebase to client — completing the two-way binding).

Questions

  1. Please provide the best practice solution for accomplishing this.

  2. Is it possible to bind the entire form (declaratively?) and avoid having to imperatively set each form field value independently upon load?

  3. I encourage pseudocode or concepts that point me in the right direction.

回答1:

iron-form is not necessary. You need to bind a <firebase-document> to an element property (representing the form) and bind the form field values to that property's sub-properties.

Also, see this todo-list example.

settings.html
<dom-module id="my-settings">
  <template>
    <firebase-document location="[[firebaseUrl]]" data="{{form}}"></firebase-document>
    <paper-checkbox checked="{{form.history}}">Save history</paper-checkbox>
    <paper-input value="{{form.name}}" label="Name"></paper-input>
    <!-- Other form fields go here -->
  </template>
  <script>
    (function() {
      Polymer({
        is: 'my-settings',
        properties: {
          form: {
            type: Object,
            notify: true
          }
        }
      });
    })();
  </script>
</dom-module>