Polymer: firebase DB not updating using firebase-e

2020-03-26 06:40发布

问题:

I'm trying to setup a firebase connection with Polymer 1.0:

<link rel="import" href="/bower/firebase-element/firebase-document.html">

  ...
  <firebase-document id='fstats'
    location="https://polymer-redux.firebaseio.com/stats"
    log="true"
    data="{{stats}}"></firebase-document>
   ...
   this.properties = {
       stats: {
          type: Object,
          observer: '_handleFirebaseStats',
          notify: true
       }
       ...
 _handleFirebaseStats(stats) {
     ...
 }

Here is how my firebase db looks like:

{
   ...
   stats: { count: 0 }
}

Now, inside the _handleFirebaseStats I receive { count: 0 }, that part works great. But I would also like to save data back to firebase. I've tried:

this.$.fstats.set({count: 2});
this.$.fstats.set({stats: {count: 2}});
this.stats.count = 2;
// etc

Anyway, whatever I try in my polymer app, FireBase is never updated. Any suggestions on how to update firebase ?

回答1:

As per my initial assumption (which was completely wrong), I thought the behavior had something to do with firebase-document element, infact the behavior is well defined inside the Polymer's Data Binding system.

Solution 1: Replace the whole property.

this.stats = {count: 2};

Solution 2: Let the system know a Path Binding has been updated.

this.stats.count = 2;
this.notifyPath('stats.count', this.stats.count);

Solution 3: Let the Polymer handle the path binding stuff for you.

this.set('stats.count', 2);

Straight from the docs:

This system “just works” to the extent that changes to object sub-properties occur as a result of being bound to a notifying custom element property that changed. However, sometimes imperative code needs to change an object’s sub- properties directly. As we avoid more sophisticated observation mechanisms such as Object.observe or dirty-checking in order to achieve the best startup and runtime performance cross-platform for the most common use cases, changing an object’s sub-properties directly requires cooperation from the user.

Specifically, Polymer provides two methods that allow such changes to be notified to the system: notifyPath(path, value) and set(path, value), where path is a string identifying the path (relative to the host element).

Also there is a Polycast where Rob Dodson explains this stuff in great detail.