【问题标题】:ActionCable Channel example 1: User appearances. Loop?ActionCable 频道示例 1:用户外观。环形?
【发布时间】:2017-05-25 16:00:19
【问题描述】:

我目前正在尝试充分了解 ActionCable。有人可以解释一下官方doc的示例代码中到底发生了什么:

# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
  end

  def unsubscribed
    current_user.disappear
  end

  def appear(data)
    current_user.appear on: data['appearing_on']
  end

  def away
    current_user.away
  end
end

结合:

# app/assets/javascripts/cable/subscriptions/appearance.coffee
App.cable.subscriptions.create "AppearanceChannel",
  # Called when the subscription is ready for use on the server
  connected: ->
    @install()
    @appear()

  # Called when the WebSocket connection is closed
  disconnected: ->
    @uninstall()

  # Called when the subscription is rejected by the server
  rejected: ->
    @uninstall()

  appear: ->
    # Calls `AppearanceChannel#appear(data)` on the server
    @perform("appear", appearing_on: $("main").data("appearing-on"))

  away: ->
    # Calls `AppearanceChannel#away` on the server
    @perform("away")


  buttonSelector = "[data-behavior~=appear_away]"

  install: ->
    $(document).on "turbolinks:load.appearance", =>
      @appear()

    $(document).on "click.appearance", buttonSelector, =>
      @away()
      false

    $(buttonSelector).show()

  uninstall: ->
    $(document).off(".appearance")
    $(buttonSelector).hide()

我不确定的是,如果 current_user.appear 创建了一个循环并因此告诉我用户通过从客户端到服务器并返回而登录?服务器端出现功能中的“on:”主题标签有什么作用? 提前致谢。

【问题讨论】:

    标签: javascript ruby-on-rails actioncable


    【解决方案1】:

    从客户端-> 服务器-> 客户端循环的意义上说,您是正确的。

    更详细地说,当连接到频道时,会调用@appear 函数。我们可以在该函数中看到,它使用了@perform,它调用了名为appear 的服务器端函数。不幸的是,在此之后它很模糊,但是假设我们想向所有用户广播此人现在在线。

    可能发生的一个例子是User 模型上的appear 函数在用户对象上设置一个布尔值以指示他们在线,并使用on 参数如下:

    # models/user.rb
    def appear(data)
      self.update(online: true, current_room: data['on'])
    end
    

    之后,我们需要一种方法让其他用户知道此人现在在线。所以首先我们必须广播这个,这可能发生在更新之后(有更好的地方放它,但为了解释数据流就足够了):

    # models/user.rb
    def appear(data)
      self.update(online: true, current_room: data['on'])
      ActionCable.server.broadcast "AppearanceChannel", {event: 'appear', user_id: self.id, room: self.current_room}
    end
    

    所以现在所有连接到外观通道的用户都会收到数据,所以我们可以将它添加到前端。假设我们只想获取某种包含用户信息的 div,如果他们在线,则给他们一个类online,否则删除该类:

    received: (data) ->
      userId = data.user_id
      eventType = data.event
      if eventType == 'appear'
        $('#user_' + userId).addClass 'online'
      else
        $('#user_' + userId).removeClass 'online'
    

    所以现在它会为所有连接到频道的用户更新,告诉他们这个用户现在在线。

    请注意,我们并没有使用用户当前所在的房间,但如果我们需要,我们可以使用data.room 获取它,并按照我们的意愿使用它。

    希望这有助于澄清事情。

    【讨论】:

    • 泰!为我清理了一切。我误解了订阅中的 current_user.appear 函数。
    猜你喜欢
    • 2023-03-27
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2016-08-23
    • 2016-05-15
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多