3
根據Sitepoint's tutorial,我在RoR應用程序中使用ActionCable,該應用程序旨在充當角色扮演的聊天室。我已經設置好了,並且如預期的那樣,消息在創建時就播出。但是,每次加載聊天室頁面時,都會爲同一用戶創建新的訂閱,從而使消息多次出現。
ActionCable多次登錄用戶
應用程序/資產/ Java腳本/渠道/ roleplays.coffee:
jQuery(document).on 'turbolinks:load', ->
messages = $('#messages')
if $('#messages').length > 0
App.global_chat = App.cable.subscriptions.create {
channel: "RoleplaysChannel"
roleplay_id: messages.data('roleplay-id')
},
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
messages.append(data)
console.log(data)
send_message: (message, roleplay_id) ->
@perform 'send_message', message: message, roleplay_id: roleplay_id
$('#new_message').submit (e) ->
$this = $(this)
textarea = $this.find('#message_body')
e.preventDefault()
if $.trim(textarea.val()).length > 1
App.global_chat.send_message textarea.val(), messages.data('roleplay-id')
textarea.val('')
return false