Non*_*714 3 javascript node.js raspberry-pi firebase firebase-realtime-database
如何使用Node.js正确设置Firebase的值事件监听器?
我正在阅读Firebase的文档,并且已成功地从我的Mac和我同时运行的Raspberry Pi连接到同一Firebase数据库的Firebase数据库上更新表格和行 ; 但是,我无法理解我需要对此段做什么才能在值事件上创建一个侦听器:
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
Run Code Online (Sandbox Code Playgroud)
这是显而易见的,我认为我需要以某种方式需要定义postElement基础上,输出:
FIREBASE WARNING: Exception was thrown by user callback. ReferenceError: postElement is not defined
Run Code Online (Sandbox Code Playgroud)
但是,我不知道postElement应该是什么,也不知道如何定义它.救命!
我做了一个非常小的程序和表来简单地更新/更改值.我改变了程序,当它改变了一行时我可以看到控制台输出.
这是我的小型用户数据变量,因此您现在尝试更改的数据很少:
var user = {
id:Number,
name:String,
number:Number
};
var users = [user];
Run Code Online (Sandbox Code Playgroud)
这是我对文档代码的更改,因此我可以在Node.js运行时在控制台输出中看到一些内容:
var userRef = firebase.database().ref('/users/user' + users[0].id);
userRef.on('value', function(snapshot){
firebase.app.updateUserInfo(postElement, snapshot.val());
console.log('Users' + users[0].name + ' changed.');//<- this is the line I added.
});
Run Code Online (Sandbox Code Playgroud)
注意:updateStarCount功能来自Firebase文档中的示例,对于那里的示例有意义,我谨慎地假设更新本地Firebase数据库...
注意2:如果updateStarCount正在做其他一些魔法,那么它是Firebase的文档缺陷,因为那里没有定义函数.任何澄清此文档的帮助将不胜感激.
为了使这个问题有助于其他人查看相同的问题,这里是一个扩展的例子,从缺少函数和变量定义的问题:
// some HTML element on the page
var postElement = document.getElementById("postElement");
// here I will assume that this function simply
// updates the contents of the element with a value
var updateStarCount = function(element, value) {
element.textContent = value;
};
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
Run Code Online (Sandbox Code Playgroud)
使用此JavaScript,您可以假设HTML页面如下所示:
<html>
<body>
<div id="postElement"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7818 次 |
| 最近记录: |