Rails Action Cable and Turbolinks: Avoid Multiple Bindings

I have code in my application.html.haml that decides whether a user subscribes to a given channel or not, depending on some user attribute.

The fact is, given that I have this part of the code in the body, when I click the link to redirect to another page, it signs the user again instead of saving the old connection, so I have the receive()method executed several 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

, , " " . , , " ". ...

, :

App.cable.subscriptions.subscriptions

( , ).

. , , .

? ?

+4
2

, MyApp.AdminNotifications, , , :

window.MyApp.AdminNotifications = class AdminNotifications
  @init: ->
    unless @initialized
      App.cable.subscriptions.create "ProductsChannel",
        received: (data) ->
          console.log 'Data Received'
      @initialized = true

API- Action .


, Turbolinks application.js, (. https://github.com/rails/rails/pull/23012#issue-125970208). , script, (if current_user.is_admin?). - , :

<meta name="current-user-is-admin" content="true">

:

window.MyApp.User = class User
  constructor: ->
    @isAdmin = @getMeta('current-user-is-admin') == 'true'

  getMeta: (name) ->
    meta = document.querySelector("meta[name=#{name}]")
    meta.getAttribute('content') if meta

, , AdminNotifications , - application.js:

document.addEventListener('turbolinks:load', ->
  window.MyApp.currentUser = new window.MyApp.User
  window.MyApp.AdminNotifications.init() if window.MyApp.currentUser.isAdmin
)

, !

0

? , .

%html
  %head
    -# other stuff
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'

    - if current_user.is_admin?
      :coffee
        MyApp.AdminNotifications.init()

  %body
    -# other stuff
0

Source: https://habr.com/ru/post/1676616/


All Articles