概要
Riot.jsとBaaSのMilkcocoaを組み合わせたチャットのサンプルです。
前提
エディタにBrackets使っています。.tagファイルのコンパイルはローカルサーバーを立てないといけないので。
手順
- 下記ソースをコピー
- プロジェクトルートの下にjsフォルダをつくってそこにriot.jsのriot+compilerを置く
- MilkcocoaのDataStoreを作成、idをchat.tagの中のMilkcocoa()に書く
- MilkcocoaのDataStoreのchatのセキュリティルールを設定する
- ローカルサーバーを立ち上げて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、少しつかめました。