firebasepolymerpolymer-2.xpolymerfire

Polymer access functions outside a function with Polymer 2.0


As the title indicates, I'd like to know how to access a function from outside. It's possible to do it in ready() by using 'this.FunctionName'. But apparently, 'this' is a 'null' value in the firebase listener.

ready() {
    super.ready();
    //this.displayData("12","13");
    console.log(this);
    var database = firebase.database();
    var myDataref = database.ref('sessions/1');
    myDataref.on('child_added', function(snapshot) {
        var message = snapshot.val();
        //console.log("Left: "+message.left);
        //console.log("Right: "+message.left);
        console.log(this);
        //this.displayData(message.left, message.right);
    });
  }

  displayData(leftData, rightData) {
    var para = document.createElement("li");
    var t = document.createTextNode("Left: "+leftData+", Right: "+rightData);
    para.appendChild(t);
    console.log(para);
    this.$.mes.appendChild(para);
  }

Code


Solution

  • The simple way is to make an alias of this and use it inside the firebase listener.

    Example:

    ready() {
      super.ready();
    
      var _this = this;
      ...
      myDataref.on('child_added', function(snapshot) {
         ...
        _this.displayData(message.left, message.right);
      });
    }
    

    The other way is to use Javascript bind method, which allow you to specify the value for this.

    Example:

    ready() {
      super.ready();
    
      ...
      myDataref.on('child_added', function(snapshot) {
         ...
        this.displayData(message.left, message.right);
      }.bind(this));
    }