teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

WebSoket受信箇所のコードを記述

2020/07/29 07:15

投稿

koki0502
koki0502

スコア19

title CHANGED
File without changes
body CHANGED
@@ -25,6 +25,7 @@
25
25
  <!== フォーム ==>
26
26
  <form class="talk_room_form">
27
27
  <input id="content" type="text" class="form-control">
28
+     <button id="button" class="btn btn-info">送信</button>
28
29
  </form>
29
30
 
30
31
  </div>
@@ -48,4 +49,64 @@
48
49
  ```
49
50
 
50
51
  メッセージを受け取った際、`addEventListener`を発火させるイベントハンドラーをご教示頂きたいです。
51
- よろしくお願いします。
52
+ よろしくお願いします。
53
+
54
+
55
+ #追加情報
56
+ WebSoket受信箇所のコードを記述します
57
+
58
+ postというアクションを持つ、chatチャンネルを作成。
59
+
60
+ chat_channel.rb
61
+ ```rb
62
+ class ChatChannel < ApplicationCable::Channel
63
+ def subscribed
64
+ stream_from 'chat_channel'
65
+ end
66
+
67
+ def unsubscribed
68
+ # Any cleanup needed when channel is unsubscribed
69
+ end
70
+
71
+ def post(data)
72
+ message = Talk.create! content: data['message'][0]
73
+ templete = ApplicationController.renderer.render(partial: 'talks/talk', locals: { talk: message })
74
+ ActionCable.server.broadcast('chat_channel', templete)
75
+ end
76
+
77
+ end
78
+
79
+ ```
80
+
81
+ chat.js
82
+ ```js
83
+ App.chat = App.cable.subscriptions.create("ChatChannel", {
84
+ connected: function() {
85
+ // Called when the subscription is ready for use on the server
86
+ },
87
+
88
+ disconnected: function() {
89
+ // Called when the subscription has been terminated by the server
90
+ },
91
+
92
+ //メッセージを受け取った際の処理
93
+ received: function(data) {
94
+ return $('#chat-index').append(data);
95
+ },
96
+
97
+ //フォームの入力を受け取る
98
+ post: function(content) {
99
+ return this.perform('post', { message: content });
100
+ }
101
+ });
102
+
103
+ document.addEventListener('DOMContentLoaded', function () {
104
+ var input = document.getElementById('content');
105
+ var button = document.getElementById('button');
106
+ button.addEventListener('click', function () {
107
+ var content = [input.value];
108
+ App.chat.post(content);
109
+ input.value = '';
110
+ })
111
+ });
112
+ ```