咖啡脚本不火的页面更改,但工作在页面加载.Rails[5]

Coffee Script not fire on page change, but works on page load. [Rails 5]

本文关键字:加载 工作 Rails 脚本 咖啡      更新时间:2023-09-26

我在我的rails项目中使用咖啡脚本,但问题是它只在我加载(刷新)页面时起作用,而不是在页面呈现时,它也应该在页面视图更改上工作。

下面是我使用的脚本:

facebook.js.coffee

jQuery ->
  $('body').prepend('<div id="fb-root"></div>')
  $.ajax
    url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
    dataType: 'script'
    cache: true

window.fbAsyncInit = ->
  FB.init(appId: env["app_id"], cookie: true)
  $('#sign_in').click (e) ->
    e.preventDefault()
    FB.login (response) ->
      window.location = '/auth/facebook/callback' if response.authResponse
  $('#sign_out').click (e) ->
    FB.getLoginStatus (response) ->
      FB.logout() if response.authResponse
    true

您可以尝试"turbolinks:load":

ready = ->
  $('body').prepend('<div id="fb-root"></div>')
  $.ajax
    url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
    dataType: 'script'
    cache: true

window.fbAsyncInit = ->
  FB.init(appId: env["app_id"], cookie: true)
  $('#sign_in').click (e) ->
    e.preventDefault()
    FB.login (response) ->
      window.location = '/auth/facebook/callback' if response.authResponse
  $('#sign_out').click (e) ->
    FB.getLoginStatus (response) ->
      FB.logout() if response.authResponse
    true

$(document).on('turbolinks:load', ready)

https://github.com/turbolinks/turbolinks#running-javascript-when-a-page-loads

document.addEventListener("turbolinks:load", function() {
  // ...
})