質問編集履歴
1
WebSoket受信箇所のコードを記述
test
CHANGED
File without changes
|
test
CHANGED
@@ -52,6 +52,8 @@
|
|
52
52
|
|
53
53
|
<input id="content" type="text" class="form-control">
|
54
54
|
|
55
|
+
<button id="button" class="btn btn-info">送信</button>
|
56
|
+
|
55
57
|
</form>
|
56
58
|
|
57
59
|
|
@@ -99,3 +101,123 @@
|
|
99
101
|
メッセージを受け取った際、`addEventListener`を発火させるイベントハンドラーをご教示頂きたいです。
|
100
102
|
|
101
103
|
よろしくお願いします。
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
#追加情報
|
110
|
+
|
111
|
+
WebSoket受信箇所のコードを記述します
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
postというアクションを持つ、chatチャンネルを作成。
|
116
|
+
|
117
|
+
|
118
|
+
|
119
|
+
chat_channel.rb
|
120
|
+
|
121
|
+
```rb
|
122
|
+
|
123
|
+
class ChatChannel < ApplicationCable::Channel
|
124
|
+
|
125
|
+
def subscribed
|
126
|
+
|
127
|
+
stream_from 'chat_channel'
|
128
|
+
|
129
|
+
end
|
130
|
+
|
131
|
+
|
132
|
+
|
133
|
+
def unsubscribed
|
134
|
+
|
135
|
+
# Any cleanup needed when channel is unsubscribed
|
136
|
+
|
137
|
+
end
|
138
|
+
|
139
|
+
|
140
|
+
|
141
|
+
def post(data)
|
142
|
+
|
143
|
+
message = Talk.create! content: data['message'][0]
|
144
|
+
|
145
|
+
templete = ApplicationController.renderer.render(partial: 'talks/talk', locals: { talk: message })
|
146
|
+
|
147
|
+
ActionCable.server.broadcast('chat_channel', templete)
|
148
|
+
|
149
|
+
end
|
150
|
+
|
151
|
+
|
152
|
+
|
153
|
+
end
|
154
|
+
|
155
|
+
|
156
|
+
|
157
|
+
```
|
158
|
+
|
159
|
+
|
160
|
+
|
161
|
+
chat.js
|
162
|
+
|
163
|
+
```js
|
164
|
+
|
165
|
+
App.chat = App.cable.subscriptions.create("ChatChannel", {
|
166
|
+
|
167
|
+
connected: function() {
|
168
|
+
|
169
|
+
// Called when the subscription is ready for use on the server
|
170
|
+
|
171
|
+
},
|
172
|
+
|
173
|
+
|
174
|
+
|
175
|
+
disconnected: function() {
|
176
|
+
|
177
|
+
// Called when the subscription has been terminated by the server
|
178
|
+
|
179
|
+
},
|
180
|
+
|
181
|
+
|
182
|
+
|
183
|
+
//メッセージを受け取った際の処理
|
184
|
+
|
185
|
+
received: function(data) {
|
186
|
+
|
187
|
+
return $('#chat-index').append(data);
|
188
|
+
|
189
|
+
},
|
190
|
+
|
191
|
+
|
192
|
+
|
193
|
+
//フォームの入力を受け取る
|
194
|
+
|
195
|
+
post: function(content) {
|
196
|
+
|
197
|
+
return this.perform('post', { message: content });
|
198
|
+
|
199
|
+
}
|
200
|
+
|
201
|
+
});
|
202
|
+
|
203
|
+
|
204
|
+
|
205
|
+
document.addEventListener('DOMContentLoaded', function () {
|
206
|
+
|
207
|
+
var input = document.getElementById('content');
|
208
|
+
|
209
|
+
var button = document.getElementById('button');
|
210
|
+
|
211
|
+
button.addEventListener('click', function () {
|
212
|
+
|
213
|
+
var content = [input.value];
|
214
|
+
|
215
|
+
App.chat.post(content);
|
216
|
+
|
217
|
+
input.value = '';
|
218
|
+
|
219
|
+
})
|
220
|
+
|
221
|
+
});
|
222
|
+
|
223
|
+
```
|