Javascript Rails Action电缆和TurboLink:避免多重绑定
我的application.html.haml中有一个代码,它决定用户是否订阅给定频道,这取决于某些用户属性 问题是,如果我的正文中有这段代码,当我单击要重定向到另一个页面的链接时,它会再次订阅用户,而不是保留旧的连接,因此我多次执行Javascript Rails Action电缆和TurboLink:避免多重绑定,javascript,ruby-on-rails,turbolinks,actioncable,turbolinks-5,Javascript,Ruby On Rails,Turbolinks,Actioncable,Turbolinks 5,我的application.html.haml中有一个代码,它决定用户是否订阅给定频道,这取决于某些用户属性 问题是,如果我的正文中有这段代码,当我单击要重定向到另一个页面的链接时,它会再次订阅用户,而不是保留旧的连接,因此我多次执行receive()方法 这是我在application.html.haml中的代码: %html %head -# other stuff = javascript_include_tag 'application', 'data-turboli
receive()
方法
这是我在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
第一次加载页面时,当我向该频道广播消息时,控制台只记录了一次“收到的数据”。
我单击一个链接重定向到另一个页面,我向该频道广播一条新消息,现在控制台记录“收到的数据”两次。到目前为止
事实上,当我在chrome的控制台上运行时:
App.cable.subscriptions.subscriptions
它返回对同一频道的多个订阅(每次我单击一个链接并被重定向到另一个页面时一次)
注意:有更多的动作电缆设置,我没有添加到这篇文章,因为它的工作良好
我怎样才能避免呢?有什么想法吗?用头而不是身体写作怎么样? 可能该事件已由TurboLink多次注册
%html
%head
-# other stuff
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
- if current_user.is_admin?
:coffee
MyApp.AdminNotifications.init()
%body
-# other stuff
看起来您只需要一个
MyApp.AdminNotifications
实例,因此您可能只需要添加一个class属性来标记该类已初始化:
window.MyApp.AdminNotifications = class AdminNotifications
@init: ->
unless @initialized
App.cable.subscriptions.create "ProductsChannel",
received: (data) ->
console.log 'Data Received'
@initialized = true
将来,您可能希望包装Action Cable API来管理您自己的订阅
在使用TurboLink时,作为一般规则,最好在application.js文件中包含尽可能多的内容,而不是在内联脚本中(请参阅:)。我猜您使用了一个内联脚本,以便有条件地运行它(
,如果当前用户是\u admin?
)。一种流行的方法是使用元标记来传递这些数据,因此在您的头脑中:
<meta name="current-user-is-admin" content="true">
最后,要从布局中删除AdminNotifications
init代码,请在application.js中包含以下内容:
document.addEventListener('turbolinks:load', ->
window.MyApp.currentUser = new window.MyApp.User
window.MyApp.AdminNotifications.init() if window.MyApp.currentUser.isAdmin
)
希望有帮助 谢谢你的赏金!如果您发现此答案可以解决您的问题,请将其标记为“已接受”。再次感谢:)
document.addEventListener('turbolinks:load', ->
window.MyApp.currentUser = new window.MyApp.User
window.MyApp.AdminNotifications.init() if window.MyApp.currentUser.isAdmin
)