【问题标题】:Difference between broadcast , broadcast_to and broadcast_for in rails 5rails 5 中的 broadcast 、 broadcast_to 和 broadcast_for 的区别
【发布时间】:2017-01-23 12:51:57
【问题描述】:

Rails Guide我发现下面三个代码sn-ps

ActionCable.server.broadcast("chat_#{params[:room]}", data)

这个简单的广播将数据发送到特定的聊天室

broadcast_to 如下图所示似乎将数据发送到当前用户订阅的频道内的所有聊天室。

WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
) 

这是另一种类型的广播broadcast_for - 我找不到任何例子。

我的问题是这三个之间的实际区别以及何时使用它们中的每一个 - 在此先感谢

【问题讨论】:

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


    【解决方案1】:

    broadcasting_for 返回一个可以重用的对象。这对于在代码/时间的不同点向同一个房间发送多条消息很有用。 broadcast最终调用broadcasting_for,所以基本一样。

    broadcast_to 脱离频道类。您在创建频道后使用它。假设您要通知博客文章 cmets 的所有订阅者。然后您的频道将如下所示:

    class CommentsChannel < ApplicationCable::Channel
      def subscribed
        post = Post.find(params[:id])
        stream_for post
      end
    end
    # use CommentsChannel.broadcast_to(@post, @comment)
    

    但是,如果您想向特定用户发送更多定向消息,那么您可以有一个名为 EmailNotifications 的类,它只关心特定用户。

    class EmailNotificationsChannel < ApplicationCable::Channel
      ...
    
    EmailNotificationsChannel.broadcast_to(
      current_user,
      title: 'You have mail!',
      body: data[:email_preview]   # some assumption of passed in or existing data hash here
    )
    

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2018-09-29
      • 2017-09-03
      相关资源
      最近更新 更多