Posted By


chrisaiv on 07/22/12

Tagged


Statistics


Viewed 828 times
Favorited by 0 user(s)

Related snippets


Firebase: Leaderboard


/ Published in: JavaScript
Save to your folder(s)

Easy-to-use leaderboard


Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3. <title>Firebase Leaderboard Example</title>
  4. <script type="text/javascript" src="http://static.firebase.com/demo/firebase.js"></script>
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  6. <link rel="stylesheet" type="text/css" href="http://www.firebase.com/css/example.css">
  7. </head>
  8. <body>
  9. <table id="leaderboardTable"></table>
  10. <input type="text" id="nameInput" placeholder="Name">
  11. <input type="text" id="scoreInput" placeholder="Score">
  12.  
  13. <div id="highestscore">
  14. Highest Score so Far: <span id="highestScoreDiv"></span>
  15. </div>
  16.  
  17. <script type="text/javascript">
  18. var LEADERBOARD_SIZE = 5;
  19.  
  20. // Build some firebase references.
  21. var rootRef = new Firebase('http://demo.firebase.com/guest253197899');
  22. var scoreListRef = rootRef.child("scoreList");
  23. var highestScoreRef = rootRef.child("highestScore");
  24.  
  25. // Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
  26. var htmlForPath = {};
  27.  
  28. // Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
  29. function handleScoreAdded(scoreSnapshot, prevScoreName) {
  30. var newScoreRow = $("<tr/>");
  31. newScoreRow.append($("<td/>").append($("<em/>").text(scoreSnapshot.val().name)));
  32. newScoreRow.append($("<td/>").text(scoreSnapshot.val().score));
  33.  
  34. // Store a reference to the table row so we can get it again later.
  35. htmlForPath[scoreSnapshot.name()] = newScoreRow;
  36.  
  37. // Insert the new score in the appropriate place in the table.
  38. if (prevScoreName === null) {
  39. $("#leaderboardTable").append(newScoreRow);
  40. }
  41. else {
  42. var lowerScoreRow = htmlForPath[prevScoreName];
  43. lowerScoreRow.before(newScoreRow);
  44. }
  45. }
  46.  
  47. // Helper function to handle a score object being removed; just removes the corresponding table row.
  48. function handleScoreRemoved(scoreSnapshot) {
  49. var removedScoreRow = htmlForPath[scoreSnapshot.name()];
  50. removedScoreRow.remove();
  51. delete htmlForPath[scoreSnapshot.name()];
  52. }
  53.  
  54. // Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
  55. var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);
  56.  
  57. // Add a callback to handle when a new score is added.
  58. scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
  59. handleScoreAdded(newScoreSnapshot, prevScoreName);
  60. });
  61.  
  62. // Add a callback to handle when a score is removed
  63. scoreListView.on('child_removed', function (oldScoreSnapshot) {
  64. handleScoreRemoved(oldScoreSnapshot);
  65. });
  66.  
  67. // Add a callback to handle when a score changes or moves positions.
  68. var changedCallback = function (scoreSnapshot, prevScoreName) {
  69. handleScoreRemoved(scoreSnapshot);
  70. handleScoreAdded(scoreSnapshot, prevScoreName);
  71. };
  72. scoreListView.on('child_moved', changedCallback);
  73. scoreListView.on('child_changed', changedCallback);
  74.  
  75. // When the user presses enter on scoreInput, add the score, and update the highest score.
  76. $("#scoreInput").keypress(function (e) {
  77. if (e.keyCode == 13) {
  78. var newScore = Number($("#scoreInput").val());
  79. var name = $("#nameInput").val()
  80. $("#scoreInput").val("");
  81.  
  82. if (name.length === 0)
  83. return;
  84.  
  85. var userScoreRef = scoreListRef.child(name);
  86.  
  87. // Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
  88. userScoreRef.setWithPriority({ name:name, score:newScore }, newScore);
  89.  
  90. // Track the highest score using a transaction. A transaction guarantees that the code inside the block is
  91. // executed on the latest data from the server, so transactions should be used if you have multiple
  92. // clients writing to the same data and you want to avoid conflicting changes.
  93. highestScoreRef.transaction(function (currentHighestScore) {
  94. if (currentHighestScore === null || newScore > currentHighestScore) {
  95. // The return value of this function gets saved to the server as the new highest score.
  96. return newScore;
  97. }
  98. // if we return with no arguments, it cancels the transaction.
  99. return;
  100. });
  101. }
  102. });
  103.  
  104. // Add a callback to the highest score in Firebase so we can update the GUI any time it changes.
  105. highestScoreRef.on('value', function (newHighestScore) {
  106. $("#highestScoreDiv").text(newHighestScore.val());
  107. });
  108.  
  109. </script>
  110. </body>
  111. </html>

URL: http://www.firebase.com/tutorial/#8

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.