如何在 rails 中根据我的观点加载咖啡脚本?

How to load a coffeescript on my views in rails?

我在申请时遇到了一些非常基本的问题。

我有一个表单,我想使用 coffeescript 进行一些处理。

我的controller/action是ProfilesController#edit_profile_photos

我的观点是:/profile/edit/profile_photos.html.erb

<span class="file-upload">
    <div class="progress" id='progress-bar' style='display:none;'>
    <div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 0%">
    <span class="sr-only" id='progress-bar-text'></span>
    </div>
</div>
<button type="button" class="btn btn-lg btn-outline-green trigger-file-upload">Upload a new photo</button>
<%= f.attachment_field :avatar, direct: true, presigned: true %>
</span>

所以,我用这个创建了一个 users.coffee 文件:

$(document).ready ->
   alert "page has loaded!"

 jQuery ->
  $(document).on "upload:start", "form", (e) ->
    $(this).find("input[type=submit]").attr "disabled", true
    $("#progress-bar").slideDown('fast')

  $(document).on "upload:progress", "form", (e) ->
    detail          = e.originalEvent.detail
    percentComplete = Math.round(detail.loaded / detail.total * 100)
    $('.progress-bar').width("#{percentComplete}%");
    $("#progress-bar-text").text("#{percentComplete}% Complete")

  $(document).on "upload:success", "form", (e) ->
    $(this).find("input[type=submit]").removeAttr "disabled"  unless $(this).find("input.uploading").length
    $("#progress-bar").slideUp('fast')

嗯。我不知道为什么我的咖啡文件没有加载。它应该与控制器同名吗? (profiles.coffee)?

谢谢

您可以将它添加到 application.js 文件以包含它以进行加载,我假设您在布局上具有标准配置,并在那里加载 application.js。

//= require users

或者您可以将该文件命名为控制器,并将其添加到您的布局中

<%= javascript_include_tag params[:controller] %> 

您有很多解决方案,如果这对您没有帮助,请在问题中添加更多信息,例如 application.js 和 layout/application.html.erb