如何从聚合物 dom 模块中的函数 Return 获取数据?

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

我是聚合物的新手,所以我在这里尝试 return 一些简单的数据,其中包含聚合物 dom-模块中的函数,其中:

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

应该显示姓名和日期,但实际上 return 什么都没有。我的代码有什么问题吗?我还在 chrome 中使用了调试器,当调用 return 时对象实际上就在那里。

<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>

<template> 中的所有数据绑定都需要包装在 <span> 中。像这样:

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

function test() 没有 return 任何东西(它是 'value' 事件处理程序 returning 东西)。

我建议您改用 firebase 聚合物元素:

https://elements.polymer-project.org/elements/firebase-element?active=firebase-collection

或将您在 'test()' 中的 firebase 代码移动到 'ready()' 函数,并使 'test()' 简单地与 "return this.username + ' ' + this.joined;" 相同,如果这符合您的意图。

TBH,由于快照似乎是一个集合(即 forEach() 暗示 不止一个 用户名+加入),所以你想要什么还不太清楚,但你的 html 似乎只需要一个用户名+加入,属性声明也反映了这一点 - 也许您还想考虑拥有一个 dom-repeat 模板?嗯,也许你只希望快照的最后一个值是相关的。有点乱,抱歉。

原始代码中有两个问题:因为 on 方法是异步的,所以您的 test 方法无法 return 一个值。调用回调时,test 已经 returned。

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

其中 combine 是这样的函数:

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

或无功能:

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

然后从 ready.

开始您现有的 test 方法
ready: function() {
  this.test();
}