學習的架構很重要,這個actioncable我大概弄了兩天晚上才搞懂,第一天晚上就照著貼程式碼。第二天忽然知道在搞什麼了。
這邊最重要的就是
後端channel
前端javascript
以下是引入的步驟
1.引用javascript套件
2.開channel,
3.在controller裡面接上ActionCable傳值
4.使用javascript去更改html
5.修理bug
影片一,Rails 6教學
https://youtu.be/nRP91C1uX-w
影片二,整套的教學
https://www.youtube.com/watch?v=tyNepRO_ERc
$rails new chat
$cd chat
$git init
$git add .
$git ci -am "init"
$yarn add jquery
$rails g scaffold message content:string
$rails db:migrate
$git ci -am "scaffold message"
ctrlp>route
root "messages#index'
設置jQuery
config/webpack/environment.js增加內容const webpack = require('webpack')
environment.plugins.prepend('Provide',new webpack.ProvidePlugin({$: 'jquery/src/jquery',jQuery: 'jquery/src/jquery'
})
)
ctrlp>application.js設置jQuery
require('jquery')
$(document).on('turbolinks:load',function(){
console.log('hello')
})
有看到console.log('hello')就表示jquery設置成功
$rails g channel room
>>>create app/channels/room_channel.rb
>>>create app/javascripts/channels/room_channel.js
ctrlp>room_channel.js
connected() {
+console.log("connected")
有看到connected就表示room_channel設置成功
ctrlp>room_channel.rb
def subscribed
stream_from "room_channel"
# stream_from "some_channel"
end
ctrlp>message_controller.rb
if @message.save
ActionCable.server.broadcast 'room_channel',content: @message.content
end
ctrlp>room_channel.js
received(data) {
console.log('receive data')
// Called when there's incoming data on the websocket for this channel
ctrlp>index.html.erb
<div id="msg">
</div>
ctrlp>room_chnnel.js
received(data) {
$('#msg').append('<div class="message">' + data.content + '</div>')
<div id="msg">
</div>
ctrlp>room_chnnel.js
received(data) {
$('#msg').append('<div class="message">' + data.content + '</div>')
debug
有個錯誤,輸入完成的時候,輸入框仍然會保留上一次的輸入結果,想辦法使用jquery解決。
var submit_messages; 設立變數
$(document).on('turbolinks:load,function(){
submit_messages()
})
submit_messages = function(){
$('message_content').on('keydown',function(event){
if(event.keyCode === 13){
console.log('we hit enter') #檢查有沒有按下enter成功
$('input').click()
event.target.value = "" #洗掉內容
event.preventDefault() #防止輸入空排
$('input').click()
event.target.value = "" #洗掉內容
event.preventDefault() #防止輸入空排
}
})
}
沒有留言:
張貼留言