(Javascript)Firebase错误,重新连接到互联网后自动多次写入数据库

时间:2017-07-31 15:04:11

标签: javascript jquery firebase firebase-realtime-database

我正在尝试编写一些代码,允许我们在互联网可用时以及用户断开连接并再次重新连接时将数据存储到数据库中。我尝试使用示例代码来帮助我:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="msapplication-tap-highlight" content="no" />
  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
  <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
  <!--/meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" /-->
  <!--/meta http-equiv="Content-Security-Policy" content="
    default-src *;
    style-src * 'unsafe-inline';
    script-src * 'unsafe-inline';
   "/-->
  <!--/External/-->
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
  <title>DeeLight</title>
</head>

<body>
  <button id="clickButton" type="submit"> Submit</button>
  <div id="result"></div>

  
  <script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "AIzaSyD41Ig37DIfH-MoF04cO4MYbcTYKL_wErQ",
      authDomain: "fypfirebase.firebaseapp.com",
      databaseURL: "https://fypfirebase.firebaseio.com",
      projectId: "fypfirebase",
      storageBucket: "fypfirebase.appspot.com",
      messagingSenderId: "787149952533"
    };
    firebase.initializeApp(config);

    // since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/004/connections');

// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/004/lastOnline');

var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', function(snap) {
         $("#clickButton").on("click", function writeUserData() {
  if (snap.val() === true) {
    // We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
    var con = myConnectionsRef.push();

    // Add this device to my connections list
    // this value could contain info about the device or a timestamp too
    con.set(true);

    // When I disconnect, update the last time I was seen online
    lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
  }
});
    });
  </script>

</body>

</html>
基本上,我创建了一个按钮,当互联网可用时,数据将存储在数据库中(点击按钮后)。 数据可以存储到数据库中。当没有互联网并且我点击了按钮时,数据将在重新连接后 时存储在数据库中。

当我再次点击(重新连接后)时出现问题,该功能似乎被触发了两次。当我断开连接并再次重新连接时......它触发了三次。

Click to see the generated result

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在firebase on()流中创建一个onclick事件只会让我感到麻烦你可以尝试让这两个独立并使用变量来跟踪在线状态吗?

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="msapplication-tap-highlight" content="no" />
  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
  <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
  <!--/meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" /-->
  <!--/meta http-equiv="Content-Security-Policy" content="
    default-src *;
    style-src * 'unsafe-inline';
    script-src * 'unsafe-inline';
   "/-->
  <!--/External/-->
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
  <title>DeeLight</title>
</head>

<body>
  <button id="clickButton" type="submit"> Submit</button>
  <div id="result"></div>

  
  <script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "AIzaSyD41Ig37DIfH-MoF04cO4MYbcTYKL_wErQ",
      authDomain: "fypfirebase.firebaseapp.com",
      databaseURL: "https://fypfirebase.firebaseio.com",
      projectId: "fypfirebase",
      storageBucket: "fypfirebase.appspot.com",
      messagingSenderId: "787149952533"
    };
    firebase.initializeApp(config);

    // since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/004/connections');

// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/004/lastOnline');

var connectedRef = firebase.database().ref('.info/connected');
var connectionStatus = false;
connectedRef.on('value', function(snap) {
     connectionStatus=snap.val()
     if(connectionStatus)
     {
      lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
     }
});

$("#clickButton").on("click", function writeUserData() {
  if (connectionStatus) {
    // We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
    var con = myConnectionsRef.push();
    con.set(true);
    
  }
    });
  </script>

</body>

</html>
&#13;
&#13;
&#13;