LoginSignup
6
6

More than 5 years have passed since last update.

Riot.jsでMilkocoaを使うサンプル

Last updated at Posted at 2016-08-08

概要

Riot.jsとBaaSのMilkcocoaを組み合わせたチャットのサンプルです。

前提

エディタにBrackets使っています。.tagファイルのコンパイルはローカルサーバーを立てないといけないので。

手順

  1. 下記ソースをコピー
  2. プロジェクトルートの下にjsフォルダをつくってそこにriot.jsのriot+compilerを置く
  3. MilkcocoaのDataStoreを作成、idをchat.tagの中のMilkcocoa()に書く
  4. MilkcocoaのDataStoreのchatのセキュリティルールを設定する
  5. ローカルサーバーを立ち上げてindex.htmlを開く
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>
<body>
    <chat></chat>

    <script type="riot/tag" src="chat.tag"></script>
    <script src="https://cdn.mlkcca.com/v0.6.0/milkcocoa.js"></script>
    <script src="./js/riot+compiler.min.js"></script>
    <script>
        riot.mount('*');
    </script>
</body>
</html>
chat.tag
<chat>
    <input type="text" id="chat_message_box">
    <button id="send_button" onclick='{send_message}'>send</button>
    <div each="{key in logs}">{key}</div>

    var milkcocoa = new MilkCocoa('{your datastore id}'),
        ds = milkcocoa.dataStore('chat');

    this.logs = [];

    var self = this;

    // 初期表示
    this.on('mount', function(){
        ds.stream().next(function(err, data){
            data.forEach(function(datum){
                self.logs.push(datum.value.message);
            });
            self.update();
        });
    });

    // 受信
    ds.on('push',function(data){
        self.logs.push(data.value.message);
        self.update();
    });

    // 送信
    this.send_message = function () {
        ds.push({"message": self.chat_message_box.value}, function(){
            self.chat_message_box.value = "";
        });
    }

</chat>

あとがき

受信部分がMilkcocoaまんまですやん。Riot.js、少しつかめました。

6
6
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
6
6