为什么所有的 coffeescript 文件总是同时执行 Rails

Why all coffeescript files always executed all at once Rails

我在 assets 文件夹中找到了每个模型的不同 coffeescript 文件。但是每次我访问一个页面时它们都会被执行,即使它来自不同的控制器。如果我继续 /insertion/new,我希望只执行 insertion.coffee,而不是我所有的 .coffee 开始。我怎样才能一次启动一个?

这是我的insertions.coffee

$(document).on "turbolinks:load", ->
  if ($('#insertion_book_search'))
    console.log("found")
  console.log($('#insertion_book_search').length)
  console.log($('#insertion_book_title').length)
  $('#insertion_books_subject').parent().hide()

那是我的 static_pages.coffee

$(document).on "turbolinks:load", ->
  console.log("Mie cose")
  $('.last_img').on 'load', ->
    natHeight = $(this).get(0).naturalHeight
    natWidth = $(this).get(0).naturalWidth
    if (natWidth > natHeight)
      $(this).css( 'width','100%')
    else
      $(this).css( 'height','100%')

我想要实现的是,当我使用插入控制器时,它只加载 insertion.coffee,而当我使用静态页面控制器时,它只加载 [=28] =]. 据我了解,当我将行 // require_tree . 添加到 /app/assets/javascript/application.js 时,我所有的咖啡都加载到我的所有视图中。

如果我删除 require 树并尝试使用 <%= javascript_include_tag ..%> 添加它们,我需要一个 .js 文件而不是咖啡。可以加载咖啡文件吗?

您应该在 application.js 清单文件中阅读有关 Rails asset pipeline. All your scripts are getting executed because most likely you have //= require_tree . directive 的更多信息。

如果你想为操作手动指定 JS 文件,你应该重新组织你的清单(至少从中删除 //= require_tree .),然后你可以使用 javascript_include_tag 手动包含 JS。更多信息 here.

注意: 如果您手动包含文件,而没有在清单中提及它们,您还应该将 Rails.application.config.assets.precompile += %w( path/to/file ) 添加到 config/initializers/assets.rb 以进行预编译.否则你会得到一个异常,告诉你这样做。更多 here.

If I remove the require tree and I try to add them with <%= javascript_include_tag ..%> I need to have a .js file and not a coffee. Is possible to load coffee files?

无论如何,您的 coffeescript 文件正在预编译为 JS。您只需指定不带扩展名的文件名。

您可以使用 coffeescript OOP 方法进行选择,下面是您的要求的详细信息和一些代码

  • 我建议你用 class 方法使用咖啡,然后用事件检查每个页面 turbolinks:load
  • 您可以查看名称为 控制器和方法例如 $(".purchase_requests.new")[0] 意味着控制器是 purchase_requests 和方法 new
  • 我还建议您阅读 brandon hilkert 博客以获取更多参考,下面是 the link

检查每个页面加载的示例 coffeescript

class App.PurchaseRequest

  renderYourJavascript: ->
    console.log "purchase request js"

$(document).on "turbolinks:load", ->
  if $(".purchase_requests.new")[0] || $(".purchase_requests.edit")[0]  
    purchase_request = new App.PurchaseRequest
    purchase_request.renderYourJavascript() 

正如您从我上面的代码中看到的那样,您可以通过检查 $(".controllers.action")[0]

来拆分

您可以将 Coffeescript 逻辑封装在 classes 中,然后在您实际需要调用该逻辑的视图中初始化 class。

所以你的咖啡文件看起来像这样:

class YourClass

   constructor: () ->
     # Anything here will be called when this object is instantiated
     @firstMethod()
     @secondMethod()

  firstMethod: () ->
    $('#some-element').click () ->
      alert('hello world')

  secondMethod: () ->
    console.log('second method triggered!')


window.YourClass = YourClass

然后,当您在特定视图中需要此逻辑时,您实际上只需初始化此对象即可:

<script>
  var yourClass = new YourClass();
</script>

您甚至可以调用特定方法,方法是将它们移出构造函数方法并在您的视图中显式调用它们:

<script>
  var yourClass = new YourClass();
  yourClass.methodNotInConstructor();
</script>