[英]Disconnect and unsubscribe Action Cable on Rails 6
This was already asked here, but it seems that the old methods ( example and example ) no longer work on Rails 6 because you cannot use App.channel
inside your app/javascript/channels/your_channel.js
.这已经在这里被问到了,但是旧方法( example和example )似乎不再适用于 Rails 6,因为您不能在
app/javascript/channels/your_channel.js
App.channel
Though, correct me if I'm wrong because I'm new to Rails.不过,如果我错了,请纠正我,因为我是 Rails 的新手。
My question is: how to disconnect or/and unsubscribe from client side on Rails 6?我的问题是:如何从 Rails 6 的客户端断开连接或/和取消订阅?
I'm especially interested in the "on page change" scenario.我对“页面更改”场景特别感兴趣。
Based on what you shared with us, I imagine you are trying to remove a subscription.根据您与我们分享的内容,我猜想您正在尝试删除订阅。 You can remove it using
consumer.subscriptions.remove
[1] .您可以使用
consumer.subscriptions.remove
[1]将其删除。
Could you share the snippet of code you have in your app/javascript/channels/your_channel.js
?您可以分享您在
app/javascript/channels/your_channel.js
中的代码片段吗?
The solution was to save the subscription on a this
variable and do the remove call if this variable is not null when page loads, then do the new subscription.解决方案是将订阅保存在
this
变量上,如果页面加载时此变量不是 null,则执行删除调用,然后执行新订阅。
// File: app/javascript/channels/your_channel.js
import consumer from "./consumer";
$(document).on('turbolinks:load', function() {
if (this.subscription) {
consumer.subscriptions.remove(this.subscription);
console.log("unsubing");
}
if ($('#hashtag').attr('data-hashtag-id')) {
var subscription = consumer.subscriptions.create({channel: "TweetsChannel", id: $('#hashtag').attr('data-hashtag-id')}, {
connected() {
console.log("we are live on: " + $('#hashtag').attr('data-hashtag-id'));
},
disconnected() {
console.log("disconecting")
},
received(data) {
$('#tweets-card').prepend(data.content)
}
});
this.subscription = subscription;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.