Firebase Notes April 2nd, 2015


A powerful API to store and sync data in realtime.

Steps

  1. Install
    <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
  2. Reference (URL for your Firebase data)
    var myDataRef = new Firebase('https://xze3eg07ah9.firebaseio-demo.com/');
  3. Write data with .set() method on a Firebase reference (write an object too) – myDataRef.set({name: name, text: text}); … In this example, when the object {name: name, text: text} is set, locations for name and text are automatically created as children of the location referenced by myDataRef
  4. Firebase can support number, boolean, and string data types — the same as a normal JavaScript object
  5. Use .push() method to append to a list – Firebase lists use chronologically-ordered, globally-unique IDs as the keys for items… This means that many clients can add to the same list without conflict
  6. We need to tell Firebase to notify us when chat messages arrive. We do this by adding a callback to the list of chat messages using the .on() method, as shown below:
    myDataRef.on('child_added', function(snapshot) {
        var message = snapshot.val();
        displayChatMessage(message.name, message.text);
    });

With Firebase, you always read data using callbacks. This allows us to guarantee that Firebase applications always update in real-time. Note that when your app starts, Firebase will call your callback for all existing chat messages and then continue to call it for any new messages that arrive. There’s intentionally no distinction between “initial” data and “new” data. This allows you to write your message handling logic once rather than having to handle these two cases separately.

<html>
 <head>
   <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
   <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
 </head>
 <body>
   <div id='messagesDiv'></div>
   <input type='text' id='nameInput' placeholder='Name'>
   <input type='text' id='messageInput' placeholder='Message'>
   <script>
     var myDataRef = new Firebase('https://xze3eg07ah9.firebaseio-demo.com/');
     $('#messageInput').keypress(function (e) {
       if (e.keyCode == 13) {
         var name = $('#nameInput').val();
         var text = $('#messageInput').val();
         myDataRef.push({name: name, text: text});
         $('#messageInput').val('');
       }
     });
     myDataRef.on('child_added', function(snapshot) {
       var message = snapshot.val();
       displayChatMessage(message.name, message.text);
     });
     function displayChatMessage(name, text) {
       $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
       $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
     };
   </script>
</body>
</html>

Resources