首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Firebase hitcounter:点击显示,但不会增加

Firebase hitcounter:点击显示,但不会增加
EN

Stack Overflow用户
提问于 2018-12-12 07:14:47
回答 1查看 42关注 0票数 0

我正在尝试制作一个显示在我的页面控制台中的点击计数器。相关代码如下:

代码语言:javascript
复制
    var database = firebase.database();



   database.ref().on("value", function(snapshot) {

      console.log("Logging snapshot.val " + snapshot.val());

      console.log("Logging hits " + snapshot.val().hits);

      var hitCounter = snapshot.val().hits;

      console.log("hitCounter is " + hitCounter)
    }, function(errorObject) {

      console.log("The read failed: " + errorObject.code);
    });

//so I can get it to display the value in the database, but not to increase.  WTF
  function showStuff() {
    $("#content").fadeIn("slow");

      hitCounter++;
      console.log("hitCounter in showstuff() function is = " + hitCounter);
      //this console log above doesn't even fire.  WTF!?
      //Ask on stack overflow some other time

      database.ref().set({
        hits: hitCounter
      });


}

正如注释所示,我可以让数据库中的数字显示,但不能增加。甚至showStuff()中的console.log也不会触发(但是淡入会触发)。到底怎么回事?

EN

回答 1

Stack Overflow用户

发布于 2018-12-12 07:44:21

您正在使用的事件回调将在每次更改数据时向其传递快照。如果需要使用showStuff函数显示该值,则必须在回调函数中调用该函数

代码语言:javascript
复制
 database.ref().on("value", function(snapshot) {
  console.log("Logging snapshot.val " + snapshot.val());
  console.log("Logging hits " + snapshot.val().hits);

  var hitCounter = snapshot.val().hits;
  console.log("hitCounter is " + hitCounter);


  showStuff();

}, function(errorObject) {

  console.log("The read failed: " + errorObject.code);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53733780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档