CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase

After walking through the previous chapters, have you felt the power of EZoApp? EZoApp can link JSON, news, Google Sheets, weather, government open data, Picasa, Flickr, … etc. Now, we will introduce an even more powerful feature: using EZoApp to link to Firebase to create a simple chat room.

Completed example: http://jqmdesigner.appspot.com/designer.html#&ref=6244329743974400

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Let's not waste more time and go directly to Firebase's official website to take a look. (https://www.firebase.com/)

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Let us register and create a new account first.

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



After you create your account, Firebase will provide you with a project. We will need to use the project name later.

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



After successful registration, Firebase will provide a 5-min tutorial. Following this tutorial, we can also link Firebase and EZoApp in five minutes.

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Before we start the tutorial, we need to write the following code in the JS editing page in EZoApp. The purpose of the code is to ensure the proper execution of external JS after it is loaded; therefore, we need to use the loadJS method. If you don't understand this, that's okay. Just copy and paste the code below. loadJS is to load external JS; put in here the function to be executed after the external JS is loaded. (Example: http://jqmdesigner.appspot.com/designer.html#&ref=6210073353256960)

(function (document, $) {

  $(document).on('pageinit', '#home', function () {
    loadJS('https://cdn.firebase.com/js/client/1.1.1/firebase.js', function () {
      // Code to be linked later
    });
  });

  function loadJS(src, callback) {
    var head = document.getElementsByTagName("head")[0],
      script = document.createElement('script');
    script.src = src;
    script.onload = callback;
    script.onerror = function (e) {
      alert("failed: " + JSON.stringify(e));
    };
    head.appendChild(script);
    head.removeChild(script);
  }

}(document, jQuery));

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Next, let us follow Firebase's 5-min tutorial and do some practice. Just follow the steps and practice them in EZoApp's JS panel.

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



After you have completed the tutorial, your code should look like this:

HTML:

<div id="messagesDiv">
  <input type="text" id="nameInput" placeholder="Name">
  <input type="text" id="messageInput" placeholder="Message">
</div>

javascript:

var myDataRef = new Firebase('https://shining-torch-42.firebaseio.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;
};



Clicking Preview, you should be able to start entering names and your message. Click Enter and the message will be sent immediately and everyone should also receive it right away. An instant messaging app is created! (Click Preview to preview the test: http://jqmdesigner.appspot.com/designer.html#&ref=6282244440195072)

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Let us go back to look at Firebase's database structure. We can see that it is completely in JSON format.

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



After the app is operative, we can do some beautification. First, put the inputs in the footer. The HTML code will become like this:

<div id="home" data-role="page">
  <div data-role="header" data-position="fixed" data-theme="b">
    <h3>Chatroom with Strangers </h3>
  </div>
  <div role="main" class="ui-content">
    <div id="messagesDiv"></div>
  </div>
  <div id="footer" data-role="footer" data-position="fixed" data-theme="b">
    <input type="text" id="nameInput" placeholder="Name">
    <input type="text" id="messageInput" placeholder="Message">
  </div>
</div>



Next, modify JS a little to put your own dialog box on the right and the dialog box for others on the left. Also, give the dialog boxes different colors. To do this, you will read the current time and save it as an id in Firebase; if the same id appears again, that means it is your own dialog box; then use CSS to place the box on the right. So, the JS should look like this:

(function (document, $) {

  var now = new Date;
  var genid = "id_gen_" + now.getTime();  // Use time as id to avoid duplicates

  $(document).on('pageinit', '#home', function () {
    loadJS('https://cdn.firebase.com/js/client/1.1.1/firebase.js', function () {

      var myDataRef = new Firebase('https://shining-torch-42.firebaseio.com/');

      $('#messageInput').keypress(function (e) {
        if (e.keyCode == 13) {
          var userid = genid;
          var name = $('#nameInput').val();
          var text = $('#messageInput').val();
          myDataRef.push({
            name: name,
            text: text,
            userid: userid  // Add an id
          });
          $('#messageInput').val('');
        }
      });
      myDataRef.on('child_added', function (snapshot) {
        var message = snapshot.val();
        displayChatMessage(message.name, message.text, message.userid);
      });

      function displayChatMessage(name, text, userid) {
        $('#messagesDiv').prepend(
          '<div class="' + userid + '">' +
          '<div class="message">' + text + '</div>' +
          '<div class="name">' + name + '</div>' +
          '</div>'
        );
        if (userid == genid) {
          $('.' + userid).addClass('me');  // Same id means it's me
        }
      };

    });
  });

  function loadJS(src, callback) {
    var head = document.getElementsByTagName("head")[0],
      script = document.createElement('script');
    script.src = src;
    script.onload = callback;
    script.onerror = function (e) {
      alert("failed: " + JSON.stringify(e));
    };
    head.appendChild(script);
    head.removeChild(script);
  }

}(document, jQuery));

CSS:

html{
  height:100%;
}
body{
  background:url('https://dl.dropboxusercontent.com/u/59597657/test/img/testbg20141022.jpg');
  background-size:cover;
  background-attachment: fixed;
  height:100%;
}
div[data-role="page"],.ui-content{
  background:rgba(0,0,0,0);
}
#footer{
  box-sizing:border-box;
  padding:0 10px;
}
.name{
  width:100%;
  text-align:left;
  font-size:12px;
  color:#fff;
  text-shadow:#000 0 0 5px,#000 0 0 2px;
  margin:10px 0 10px 10px;
}
.me .name{
  color:#ff5;
  text-align:right;
  margin:10px 15px 10px 0;
}
.message{
  text-shadow:none;
  box-sizing:border-box;
  width:100%;
  padding:10px 20px;
  border-radius:10px;
  margin-bottom:15px;
  background:rgba(255,255,255,.6);
  position:relative;
  color:#000
}
.message::before{
  content:'';
  width:0;
  height:0;
  position:absolute;
  bottom:-20px;
  left:15px;
  border-width:10px 7px;
  border-style:solid;
  border-top-color:rgba(255,255,255,.6);
  border-left-color:rgba(0,0,0,0);
  border-right-color:rgba(0,0,0,0);
  border-bottom-color:rgba(0,0,0,0);
}
.me .message{
  background:rgba(255,255,150,.6);
}
.me .message::before{
  border-top-color:rgba(255,255,150,.6);
  left:auto;
  right:15px;
}



Example completed. Click Preview to preview: http://jqmdesigner.appspot.com/designer.html#&ref=6215586547761152

CHAPTER 23 - Create Chat with Strangers App by Linking to Firebase



Continue reading CHAPTER 24 - Link Parse (deprecated)
Or Return to Table of Contents


results matching ""

    No results matching ""