I have a code in my application.html.haml that decides whether to subscribe the user to a given channel or not, depending on some user attribute.
The thing is that, given I have this piece of code in the body, when I click a link to be redirected to another page, it subscribes the user again instead of keeping the old connection, so I have the receive()
method being executed multiple times.
This is my code in application.html.haml
:
%html
%head
-# other stuff
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
%body
-# other stuff
- if current_user.is_admin?
:coffee
MyApp.AdminNotifications.init()
assets/javascripts/notifications/admin_notifications.js.coffee
window.MyApp.AdminNotifications = class AdminNotifications
@init: ->
App.cable.subscriptions.create "ProductsChannel",
received: (data) ->
console.log 'Data Received' # This is being executed multiple times
The first time the page is loaded, when I broadcast a message to that channel, the console is logging "Data Received" just once. I click a link to be redirected to another page, I broadcast a new message to that channel, and now the console is logging "Data Received" twice. And so far so on...
In fact, when I run on the chrome's console:
App.cable.subscriptions.subscriptions
It returns multiple subscriptions to the same channel (once for every time I clicked on a link and got redirected to a different page).
Note: There is more action cable setup that I am not adding to this post because it's working fine.
How can I avoid that? Any ideas?