Niklas Lang Niklas Lang - 1 year ago 114
Javascript Question

Polymer data binding to text from Firebase snapshot

I am working on a project that makes use of Firebase Authentication and

<firebase-query>
from the
polymerfire
elements. I use data binding in many places throughout my application and never had this problem.

I bind the user object, which was created when a user authenticated, in many places to receive the name of my users. The following code shows a custom element. In there, I am trying to bind besides the user object the Firebase snapshot to a property that is of type
Object
.

When I
console.log()
the
vidobj
property, it displays the whole object. However, I am unable to bind it to my text. Although, the same works for the user object property.

I believe this has something to do with the lifecycle in Polymer. Should the property not update automatically even though the value might be created later?

The following screenshot displays the two
console.log
's
with the content of the
vidobj
:

enter image description here



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

<dom-module id="my-singlevideo">
<template>
<style>
:host {
display: block;
}
</style>

<firebase-auth user="{{user}}"></firebase-auth>
<iron-localstorage
id="localstorage"
name="my-app-storage"
value="{{localUserDetails}}">
</iron-localstorage>

<h1>Name: [[user.displayName]]</h1>
<h1>Video Title: [[vidobj.title]]</h1>

</template>

<script>
Polymer({
is: 'my-singlevideo',

properties: {
user: {
type: Object,
},
localUserDetails: {
type: Object,
},
vidobj: {
type: Object,
},
},

ready: function() {

this.$.localstorage.reload();
var videoId = this.localUserDetails.lastClickedVid;

firebase.database().ref('/videos/' + videoId).once('value', function(snapshot) {
this.vidobj = snapshot.val();
console.log(this.vidobj);
console.log(this.vidobj.title);
});
},

});
</script>
</dom-module>

Answer Source

Your Firebase callback's context is not bound to your Polymer object, so you're actually setting vidobj on the outer context (usually the Window object).

To fix this, use Function#bind like this:

ready: function() {
  // ...
  firebase.database().ref('/videos/' + videoId).once('value',
    function(snapshot) {
      this.vidobj = snapshot.val();
      console.log(this.vidobj);
      console.log(this.vidobj.title);
    }.bind(this)
  );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download