Search code examples
javascriptpolymerweb-component

How to Return data from a function inside a polymer dom-module?


I'm new to polymer so here I'm trying to return some simple data with a function inside a polymer dom-module where:

Username and date: <p>{{test()}}</p>

should display a name and a date, but actually is returning nothing. Anything wrong in my code? I also used the debugger in chrome and the object is actually there when return is called.

<dom-module id="user-list-module">
  <template>
      <paper-material elevation="1">
        Username and date: <p>{{test()}}</p>
      </paper-material>
  </template>

  <script>
    (function() {
      Polymer({
        is: 'user-list-module',
        properties: {
            username: String,
            joined: Date,
        },
        test: function () {
          this.username = '';
          this.joined = '';
          var fb = new Firebase('https://blistering-torch-8317.firebaseio.com/users/public/');
          fb.on('value', function(snapshot) {
            snapshot.forEach(function(childSnapshot){
              var key = childSnapshot.key();
              var childData = childSnapshot.val();
              this.username = childData.username;
              this.joined = childData.date.split(' ').slice(0, 4).join(' ');
              return this.username + ' ' + this.joined;
            });
          })
        }
      });
    })();
  </script>
</dom-module>

enter image description here


Solution

  • There are two issues in the original code: because the on method is async, there's no way for your test method to return a value. By the time your callback is invoked, test has already returned.

    Username and date: <p><span>{{combine(firstname, joined)}}</span></p>
    

    Where combine is a function like this:

    combine: function(first, date) {
      return first + ' ' + date;
    }
    

    Or without the function:

    Username and date: <p><span>{{firstname}}</span> <span>{{joined}}</span></p>
    

    Then kick off your existing test method from ready.

    ready: function() {
      this.test();
    }