LoginSignup
17
17

More than 5 years have passed since last update.

Firebaseを使ってとりあえずチャットを作ってみる

Last updated at Posted at 2016-02-11

Firebase とは

リアルタイム通信ができたりするものらしいです。
この文章を書いてる段階では、まだ使っていません。
https://www.firebase.com/

まずログイン

サインアップしてない人はサインアップ
image

ログインしたら、Dashboardが自動で表示されました。

image

APP を追加する

image

追加こんな感じになります

image

簡易チャットを作る

http://lite.runstant.com/
runstant 等のブラウザ上でJSを編集してすぐに実行できるサービスを使います。
今回はrunstantを使用します。

完成形はこんな感じです。

firechattest.gif

HTMLコード

<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
でFirebaseのライブラリを読み込むだけで準備完了です。


<!doctype html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <title>${title}</title>
    <meta name="description" content="${description}" />

    <style>${style}</style>
    <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
    <script>${script}</script>
  </head>
  <body>
    name:<input type="text" name="name" id="name" value="" />
    message:<input type="text" name="message" id="message" value="" />
    <button type="button" id="send">send</button>
    <div id="log"></div>
  </body>
</html>



js のコード



window.onload = function() {
  var fb = new Firebase("https://<自分で追加したAPPのURL部分>.firebaseio.com/");

  var chatStore = fb.child('chat');

  chatStore.on('child_added', function(dss) {
    addMessage(dss.val());
  });

  var inputName = document.getElementById('name');
  var inputMessage = document.getElementById('message');
  var sendButton= document.getElementById('send');

  function send (){
    chatStore.push({
      name:inputName.value,
      message:inputMessage.value,
    });
  }

  sendButton.onclick = send;

  inputName.onkeydown = function(e){
    if(e.keyCode === 13){
      inputMessage.focus();
    }
  };

  inputMessage.onkeydown = function(e){
    if(e.keyCode === 13){
      send();
    }
  };

  var logArea = document.getElementById('log');
  function addMessage(value){
    var div= document.createElement('div');
    div.textContent = value.name + ': ' + value.message;
    logArea.appendChild(div);
  }
};



コード(全部)

ちょっと解説

var nanika = fb.child('なにか')
これは、JS的に解釈すると
var nanika = {};
という感じです。
JSのオブジェクト的な構造のデータストアがFirebase上に作られています。

nanika.push(value)
これは、pushした時点で適当なkeyが割り振られ、そのkeyに紐付けてvalueが追加されます。
nanika[適当なkey] = value という感じに追加されます。
nanikaの構造は


nanika = {
  適当なkey: value,
}

となり、
valueがオブジェクトなら、さらに深い階層のデータストアが作れます。

nanika.on('child_added', function(datasnapshot){});

onはイベントを追加します。
child_addedイベントはnanikaにデータが追加されたときに発生し、コールバック関数の引数には、 datasnapshot(追加されたデータを持ったオブジェクト)が渡されます。
また、fb.child('nanika')でnanikaに接続した時も、今までに追加されているデータがあれば、追加した順にchild_addedイベントが発生します。

dss = datasnapshot からkeyや追加されたデータを受け取るには以下のようにします。

keyを得る
dss.key()

値を得る
dss.val()

このぐらい覚えれば、とりあえず程度のチャットが作れました!

17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17