问题
Here is the file, containing what should receive from the Message Relay Job that successfully loads on the server.
App.chatrooms = App.cable.subscriptions.create "ChatroomsChannel",
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) ->
console.log(data)
active_chatroom = $("[data-behavior='messages'][data-chatroom-id='#{data.chatroom_id}']").append("<div><strong>#{data.username}:</strong> #{data.message}</div>")
if active_chatroom.length > 0
active_chatroom.append("<div><strong>#{data.username}:</strong> #{data.body}</div>")
else
$("[data-behavior='chatroom-link'][data-chatroom-id='#{data.chatroom_id}']").css("font-weight", "bold")
# Called when there's incoming data on the websocket for this channel
send_message: (chatroom_id, body) ->
@perform "send_message", {chatroom_id: chatroom_id, body: body}
When the server loads with a message it shows the right message in the message relay job.
Here's the other coffee script for the file.
Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).on 'turbolinks:load', ->
$('#new_groupmessage').on 'keypress', (e) ->
if e && e.keyCode == 13
e.preventDefault()
$(this).submit()
$('#new_groupmessage').on "submit", (e) ->
e.preventDefault()
chatroom_id = $("[data-behavior='messages']").data("chatroom-id")
body = $("#groupmessage_body")
App.chatrooms.send_message(chatroom_id, body.val())
body.val("")
Just so you can see the html:
<div data-behavior='messages' data-chatroom-id='<%= @chatroom.id %>' class=messages style="margin-left: 140px; border-left: 1px black solid; padding-left: 2px;">
<% @chatroom.groupmessages.order(created_at: :desc).limit(100).reverse.each do |groupmessage| %>
<%= render groupmessage %>
<% end %>
</div>
<%= form_for [@chatroom, Groupmessage.new] do |f| %>
<%= f.text_area :body, rows: 1, class: "form-control", autofocus: true %>
<%= f.submit %>
<% end %>
Pretty straightforward data forms and display.
class MessageRelayJob < ApplicationJob
queue_as :default
def perform(message)
ActionCable.server.broadcast "chatrooms:#{message.chatroom.id}", {
username: message.user.username,
body: GroupmessagesController.render(message),
chatroom_id: message.chatroom.id
}
# Do something later
end
end
And the message relay job is clean and simple too.
来源:https://stackoverflow.com/questions/55545948/how-to-ensure-the-javascripts-channels-chatrooms-coffee-is-loading-and-receive