Polymer 1.0: Two-way data binding: <iron-form> to/from Firebase

倾然丶 夕夏残阳落幕 提交于 2020-01-04 05:20:01

问题


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>


来源:https://stackoverflow.com/questions/33598530/polymer-1-0-two-way-data-binding-iron-form-to-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!