firebasepolymerfirebase-realtime-databasefirebase-polymer

Syncing a paper-input with firebase using polymer


How is this for a solution for syning the data from a paper input to a firebase database.

properties: {
            teamid: {
                type: String,
                value: null
            },
            formid: {
                type: String,
                value: null
            },

            metaName: {
                type: String, 
                value: null,
                observer: '_updateMetaName'
            }
        },


        _updateMetaName: function(metaName) {
            var path = 'formModel/' + this.teamid + '/' + this.formid + '/meta/name';

            firebase.database().ref(path).set(metaName);
        },

The data metaName comes from a a paper-input element

<paper-input value="{{metaName}}"></paper-input>

I'm using an observer over the on-change attribute because I hate the idea that a user must move out of an input for it to persist. I've also chosen not to use PolymerFire because i dosen't have some features I need and its not production ready.

I also don't like the idea that the observer runs multiple times before any data has been changed. And that should, i thought, break it but its working to my surprise.

What other options do I have? Are their any disadvantages to my current solution?


Solution

  • One disadvantage is that every keystroke fires off a request to Firebase, which could be inefficient (a waste of CPU and bandwidth).

    To address this, you could debounce the callback with this.debounce(jobName, callback, wait), as shown in the following demo.

    HTMLImports.whenReady(_ => {
      "use strict";
    
      Polymer({
        is: 'x-foo',
        properties : {
          metaName: {
            type: String,
            value: 'Hello world!',
            observer: '_metaNameChanged'
          }
        },
        _setFirebaseMetaName: function(metaName) {
          var path = 'formModel/' + this.teamid + '/' + this.formid + '/meta/name';
          //firebase.database().ref(path).set(metaName);
          console.log('metaName', metaName);
        },
        _metaNameChanged: function(metaName) {
          this.debounce('keyDebouncer',
                        _ => this._setFirebaseMetaName(metaName),
                        500);
        }
      });
    });
    <head>
      <base href="https://polygit.org/polymer+1.5.0/components/">
      <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="paper-input/paper-input.html">
    </head>
    <body>
      <x-foo></x-foo>
    
      <dom-module id="x-foo">
        <template>
          <paper-input label="Meta Name" value="{{metaName}}"></paper-input>
        </template>
      </dom-module>
    </body>

    codepen