最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set a listener on Firebase value event? - Stack Overflow

programmeradmin4浏览0评论

How to properly set up a value event listener with Firebase, using Node.js?

I'm reading through Firebase's documents, and have successfully been able to update tables and rows on my Firebase database from both my Mac, and my Raspberry Pi running at the same time, connected to the same Firebase database; however, I'm not able to understand what I need to do with this segment for making a listener on a value event:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
    updateStarCount(postElement, snapshot.val());
});

It's evident to me that I need somehow need to define postElement based on the output:

FIREBASE WARNING: Exception was thrown by user callback. ReferenceError: postElement is not defined

However, I have not idea what postElement is supposed to be, nor how to define it. Help!

I've made a very small program and table to simply update/change values. And I changed the program to I can see up console output when a row it changed.

This is my small user data variable, just so you now how little data I'm trying to change:

var user = {
    id:Number,
    name:String,
    number:Number
};

var users = [user];

And this is my change to the documentation code, so I can see something in the console output while Node.js is running:

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.
});

NOTE: updateStarCount function is from the example in the Firebase documentation, meaningful to the example there, which I cautiously assume updates the local Firebase db...

NOTE2: If updateStarCount is doing some other magic, then it is a documentation flaw with Firebase, because the function isn't defined there. Any help clarifying this documentation would be greatly appreciated.

How to properly set up a value event listener with Firebase, using Node.js?

I'm reading through Firebase's documents, and have successfully been able to update tables and rows on my Firebase database from both my Mac, and my Raspberry Pi running at the same time, connected to the same Firebase database; however, I'm not able to understand what I need to do with this segment for making a listener on a value event:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
    updateStarCount(postElement, snapshot.val());
});

It's evident to me that I need somehow need to define postElement based on the output:

FIREBASE WARNING: Exception was thrown by user callback. ReferenceError: postElement is not defined

However, I have not idea what postElement is supposed to be, nor how to define it. Help!

I've made a very small program and table to simply update/change values. And I changed the program to I can see up console output when a row it changed.

This is my small user data variable, just so you now how little data I'm trying to change:

var user = {
    id:Number,
    name:String,
    number:Number
};

var users = [user];

And this is my change to the documentation code, so I can see something in the console output while Node.js is running:

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.
});

NOTE: updateStarCount function is from the example in the Firebase documentation, meaningful to the example there, which I cautiously assume updates the local Firebase db...

NOTE2: If updateStarCount is doing some other magic, then it is a documentation flaw with Firebase, because the function isn't defined there. Any help clarifying this documentation would be greatly appreciated.

Share Improve this question edited Dec 25, 2016 at 18:45 NonCreature0714 asked Dec 25, 2016 at 18:28 NonCreature0714NonCreature0714 6,01410 gold badges33 silver badges55 bronze badges 6
  • Where is this updateStarCount function ing from? It's definitely not from Firebase. – vzsg Commented Dec 25, 2016 at 18:33
  • @vzsg if you check the link to the Firebase page and search for updateStarCount you'll find it in the linked page. – NonCreature0714 Commented Dec 25, 2016 at 18:35
  • Ah, I see. I should have phrased it as "not from the Firebase SDK". This is just example code, not much more concrete than pseudocode. The idea there assumes that you have a function that updates an HTML element with the results — which you must replace with your own logic in a real application. – vzsg Commented Dec 25, 2016 at 18:36
  • @vzsg Gotcha... I guess an expansion to my question is, how to understand this documentation example? Everything is pretty clear up until that point. – NonCreature0714 Commented Dec 25, 2016 at 18:41
  • Imagine a web application where there are posts with ratings that are displayed as stars... Note that you are reading the Web guide (browser JavaScript), not the Node Admin SDK's guide. – vzsg Commented Dec 25, 2016 at 18:45
 |  Show 1 more ment

2 Answers 2

Reset to default 9

In order to make this question helpful for other people looking into same problem, here's an extended example from the question with missing functions and variables defined:

// 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());
});

With this JavaScript you can assume HTML page which looks like this:

<html>
  <body>
    <div id="postElement"></div>
  </body>
</html>

Following IgorNikolaev's example... In order to make this post more useful to people having the same problem with Node.js on Raspberry Pi's or as a standalone app (not for a web page).

Thanks to @vzsg, the Firebase Admin SDK may be better suited to my situation.

Steps to create a fully working example are...

This only covers writing to a database, results of which can be seen when logged into Firebase's console.

First, create Firebase admin authentication, then:

var admin = require("firebase-admin");
admin.initializeApp({
    credential:admin.credential.cert("/path/to/credential/cert.json"),
    databaseURL: "databaseURLhere"
});

var db = admin.database();
var ref = db.ref("/");
console.log('DB ref: ' + ref);

var usersRef = ref.child("users");

Use set to create new values in the database. But be careful, set overwrites pre-existing values.

usersRef.set({ //With pletion callback.
    alanisawesome: {
      date_of_birth: "June 23, 1912",
      full_name: "Alan Turing"
    },
    gracehop: {
      date_of_birth: "December 9, 1906",
      full_name: "Grace Hopper"
    }
  },
  function(error) { //NOTE: this pletion has a bug, I need to fix.
    if (error) {
      console.log("Data could not be saved." + error);
    } else {
      console.log("Data saved successfully.");
    }
});

Append new columns (or change current data) to row with update, but be extra careful to give the paths to column, otherwise all previous columns are overwritten, instead of appending to the table:

usersRef.update({
    "alanisawesome/nickname": "Alan The Machine",
    "gracehop/nickname": "Amazing Grace"
  },
  function(error){
    if(error){
      console.log("Data could not be updated." + error);
    } else {
      console.log("Data updated successfully.");
    }
  });
发布评论

评论列表(0)

  1. 暂无评论