在同一 App.cable.subscription 中收到多个回调

Multiple received callbacks in same App.cable.subscription

我正在开发一个聊天功能,我希望在同一个广播频道中有几个单独的事件:

随着消息的正常流动。我已经到了这样的地步,其中每一个事件都正确地触发了 received: (data) -> 回调,并正确地显示给正确的用户。

所有事件都在客户端使用不同的触发器提交,例如 keydown、submit 等并进行不同的处理,但它们最终都命中相同的接收回调。我如何在同一个 received(data) -> 回调中确定这些事件的范围,以涵盖用户停止输入(但未发送消息?

时的功能

例如,当用户键入:

$(".new_im_message").on("focusin",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_typing(values);
});

适当处理然后点击收到的回调:

  received: (data) ->
    $(".user_is_typing").show();

用户不再输入,也没有消息发送

$(".new_im_message").on("blur",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_blur(values);
});

适当处理然后收到点击:

  received: (data) ->
    $(".user_is_typing").show(); 
    $(".user_is_typing").hide(); <<<< can't hide and show at the same time..

如何拆分活动?

  1. 是否可以在同一个频道内接收到多个回调? received1(data) received2(data) 等等
  2. 如果没有,我可以根据哪种数据类型 (is_typing) (is_blur) 触发接收到的回调来解决它吗?
  3. 如果不是,我真的需要将它完全分成不同的频道吗?

谢谢!

每当您在 JS 代码中调用 perform()(即当用户键入时)时,我建议传递操作;即它可能看起来像

@perform('typing')

然后在您的频道(ruby 代码)中,您需要有一个方法来响应上述操作:

def subscribed
  stream_from 'someidentifier'
  # this line is optional. I just added this to immediately notify everyone in the chatroom that a new user joined in to the chatroom
  ActionCable.server.broadcast 'someidentifier', action: 'subscribed', user_id: current_user.id
end

# this will be called by the JS `@perform('typing')` above
def typing
  # we then broadcast to everyone in that chat room (a.k.a "someidentifier" chatroom), that a specific user is currently typing a message. Modify this as you wish
  ActionCable.server.broadcast 'someidentifier', action: 'typing', user_id: current_user.id
end

def blur
  ActionCable.server.broadcast 'someidentifer', action: 'blur', user_id: current_user.id
end

然后返回您的 JS 代码中的 received(data) 函数,我们会将操作分离到适当的响应逻辑中:

received: (data) ->
  switch data.action
    when 'subscribed'
      # do something when a new user (data.user_id) has joined in the chatroom
      console.log(data.user_id)
    when 'typing'
      # do something when a user (data.user_id) is typing 
      console.log(data.user_id)
    when 'blur' 
      # do something when a user (data.user_id) stopped typing
      console.log(data.user_id)