我是 polymer 的新手,所以在这里我尝试使用 polymer dom 模块内的函数返回一些简单的数据,其中:
Username and date: <p>{{test()}}</p>
应该显示名称和日期,但实际上没有返回任何内容。我的代码有什么问题吗?我还在 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>
最佳答案
函数 test() 不返回任何内容(它是返回某些内容的“value”事件处理程序)。
我建议您改用 firebase polymer 元素:
https://elements.polymer-project.org/elements/firebase-element?active=firebase-collection
或者将“test()”中的 firebase 代码移至“ready()”函数,并将“test()”简单地设置为“return this.username + ' ' + this.joined;”,如果这符合您的意图。
TBH,不太清楚您想要什么,因为快照似乎是一个集合(即 forEach() 意味着多个用户名+加入),但您的html似乎只需要一个用户名+joined,属性声明也反射(reflect)了这一点 - 也许您还想考虑使用 dom-repeat 模板?嗯,也许您只希望快照的最后一个值是相关的。有点困惑,抱歉。
关于javascript - 如何从 polymer dom 模块内的函数返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33002056/