【问题标题】:Multiple received callbacks in same App.cable.subscription在同一个 App.cable.subscription 中收到多个回调
【发布时间】:2017-07-09 12:51:59
【问题描述】:

我正在开发一个聊天功能,我想在同一个广播频道中为:

  • 消息已送达
  • 用户正在输入
  • 用户已阅读消息

随着消息的正常流动。我已经到了这样的地步:这些事件中的每一个都正确地触发了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. 如果不需要,我真的需要将它完全分成不同的渠道吗?

谢谢!

【问题讨论】:

    标签: ruby-on-rails actioncable ruby-on-rails-5


    【解决方案1】:

    每当您在 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)
    

    【讨论】:

    • 这显然是正确的答案。像魅力一样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多