Rails 4 CoffeeScript 在预编译时不执行

Rails 4 CoffeeScript not executing when precompiled

我有一个 Rails 4 应用程序,其中包含一些 Coffeescript,主要用于在选择另一个列表中的项目时更新列表 - 非常基本的东西。

该脚本在开发中完美运行。但是,一旦预编译,即使我在预编译资产文件中看到实际代码,它也不会运行。

我将代码缩减到一个非常小的范围,所以它所做的只是在组合框已更改但仍无法正常工作时显示警告。我还从 assets/javascript 目录中删除了所有 .coffee 文件,只留下这个 Coffeescript 文件和 application.js 文件,以确保与其他 .coffee 文件没有冲突。

我也怀疑 turbolinks,然后我删除了它,但仍然没有改变。

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .

attendance.coffee

  $('#season_id').on "change", ->
     alert('Success!')

表格来自 app/views/attendances/_form.html.erb

<div class="container">
    <form action="/attendances/get_attendance_sheet" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="&#x2713;" />       <table class="table">
            <tr>
                <td>Saison:</td>
                <td><select name="season_id" id="season_id" class="form-control"><option value="">Choisir une saison</option><option value="1">Gadbois 2015</option></select></td>
                <td>Entraînement du:</td>
                <td><select name="session_id" id="session_id" class="form-control"><option value="">Choisir une date d&#39;entraînement</option><option value=""></option></select></td>
                <td><input type="submit" name="commit" value="Ouvrir" class="btn btn-success" /></td>
            </tr>
        </table>
</form></div>

检查你编译的 javascript 文件 (http://yousite.net/application-[DIGEST].js 。是否有 season_id?如果 season_id 存在,则尝试更改你的代码:

$ ->
  $('#season_id').on "change", ->
     alert('Success!')

终于找到问题了,感谢@itsnikolay。问题是由于另一个 javascript 文件抛出异常。通过将它们全部编译到一个文件中,异常将使整个脚本停止 运行,因此不会执行 Coffescripts。

在这种特殊情况下,这是由于 gem rails-assets-tether 缺少 bootstrap 库提供的工具提示。

在调试模式下,由于所有 javascript 文件都是独立加载的,因此一个文件的异常不会影响其他文件的加载。