【问题标题】:How to pass element id to cable subscription?如何将元素 ID 传递给有线电视订阅?
【发布时间】:2019-05-23 22:54:10
【问题描述】:

我已设置 ActionCable 并使用通用消息通道。但是,我需要将频道订阅限制为单个消息。我应该如何将 message_id 传递给订阅?

我有一个包含正在查看/订阅的 message_id 的数据属性。

comment_channel.js

import consumer from "./consumer"
var get_id = $('#messages').data('message-id')

consumer.subscriptions.create({
  channel: "CommentChannel", message_id: get_id

}, {

 connected() {
 console.log('connected to the comment channel')
},

disconnected() {
console.log('disconnected to the comment channel')
},

received(data) {
  console.log(data);
  $('section#comments').append(data['comment']);
}
});

评论频道

class CommentChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "message_comments"
    # params['message_id'] should get passed in as subscription.create param
    stream_from "message:#{ params['message_id'] }:comments"
  end

  def unsubscribed
  end
end

评论工作

class CommentRelayJob < ApplicationJob
  def perform(comment)
    ActionCable.server.broadcast("message:#{ comment.message_id }:comments", comment: CommentsController.render(partial: 'comments/comment', locals: { comment: comment }))
  end
end

上面的get_id失败了

 comment_channel.js:6 Uncaught ReferenceError: $ is not defined

如何限制对特定消息的订阅?

【问题讨论】:

  • 它抱怨 jQuery 尚未加载。您可以在 jQuery 就绪回调中添加所有代码,只需使用 vanilla javascript document.getElementById('messages').dataset.messageId
  • 即使是普通的 JS 也会失败,因为 document 是 nil。此代码在 DOM 被可操作加载后很久才调用...我犹豫是否将其包装在 ready() 回调中,因为我认为这可能会导致其他问题。但是,我想我会试一试。在我看来,还有另一种方法可以将值传递给 x_channel.js 文件。
  • 我尝试的一切都以各种错误结束,因为文档始终为零

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


【解决方案1】:

我最终使用

获取了 url id
var pathArray = window.location.pathname.split('/');
var secondLevelLocation = pathArray[2];

然后将其作为订阅的参数放入

consumer.subscriptions.create({ 
  channel: "CommentChannel", 
  message_id: secondLevelLocation
}, ...

据我所知,您不能在此文件中使用 ready() 回调...无论我尝试什么都会导致错误。

【讨论】:

    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2019-09-10
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多