如何将元素 ID 传递给有线电视订阅?

How to pass element id to cable subscription?

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

我有一个包含 message_id 的数据属性 viewed/subscribed。

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

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

我最终使用

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

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

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

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