gpt4 book ai didi

javascript - Rails 5 Action Cable 具有多个参数

转载 作者:行者123 更新时间:2023-11-28 06:10:47 25 4
gpt4 key购买 nike

David has a great video on how to use Action Cable for Rails 5 ,对我来说,我使用的是 Rails 5 上的 beta 3 版本。

问题是,Action Cable 是否仅适用于只有一个参数作为数据传递的聊天应用程序?我可以向 speak 传递多个参数吗?

RoomChannel(咖啡):

App.room = App.cable.subscriptions.create "RoomChannel",
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) ->
alert data['message']
# Called when there's incoming data on the websocket for this channel

speak: (message) -> # Could I pass in more than one params?
@perform 'speak', message: message

room_channel.rb:

# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading.
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end

def unsubscribed
# Any cleanup needed when channel is unsubscribed
end

def speak(data)
ActionCable.server.broadcast 'room_channel', message: data['message']
end
end

如果我可以传入多个参数,它适合这里的哪里:

App.room.speak("foo bar"); # one param so far here.

编辑:

我现在收到两个对象的警报:[object object]

App.room.speak(
{
data1: "Data 1 mate",
data2: "Data 2 mate"
}
)

房间.咖啡:

received: (data1, data2) ->
alert data1['message']

room_channel.rb:

def speak(data1, data2)
ActionCable.server.broadcast 'room_channel', message: data1['message'], data2['message']
end

控制台:

RoomChannel#speak({"message"=>{"data1"=>"Data 1 mate", "data2"=>"Data 2 mate"}})

最佳答案

要将另一个参数传递给可操作服务器,您可以传递 Javascript 对象。

然后在服务器端,这个 Javascript 对象被表示为一个哈希值。

示例:

客户端

App.room.speak(
{
param1: "Data 1 mate",
param2: "Data 2 mate"
}
)

服务器端

def speak(data)
ActionCable.server.broadcast 'room_channel', param1: data['param1'], param2: data['data2']
end

然后返回给客户端

received: (data) ->
alert data['param1']
alert data["param2"]

关于javascript - Rails 5 Action Cable 具有多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com