【问题标题】:RuntimeEror when using asset .js.coffee file使用资产 .js.coffee 文件时出现 RuntimeEror
【发布时间】:2011-12-14 21:16:55
【问题描述】:

我刚刚开始使用 rails 3.1 和 jQuery/coffee 脚本。我有一段 js 代码,当包含在我的视图中的标签中时可以工作,但是当包含在 app/assets/javascripts/post.js.coffee 中时,它会引发以下错误:

ExecJS::RuntimeError in Posts#new

显示 /home/chris/RailsDev/blog/app/views/layouts/application.html.erb 在哪里 第 10 行提出:

第 7 行的保留字“function”(在 /home/chris/RailsDev/blog/app/assets/javascripts/post.js.coffee)

这行得通:

app/views/posts/new.html.erb

<%= form_for [@user, @post] do |f| %>
      <div class="field">
        <%= f.label :title %><br />
        <%= f.text_field :title %>
      </div>
      <div class="field">
        <%= f.label :content %><br />
        <%= f.text_area :content %>
      </div>
      <div class="field">
        <label for="forward_date">Post in the future?</label>
        <%= check_box_tag 'forward date' %>
        <div id="post_date" style="display: none;">
          <%= f.label :post_date %>
          <%= f.datetime_select :post_date %>
        </div>
      </div>
      <div class="actions">
        <%= f.submit "Create" %>
      </div>
    <% end %>
    <script>
      $("#forward_date").change(function() {
        if($(this).is(":checked")) {
          $("#post_date").show("slow");
        } else {
          $("#post_date").hide("slow");
        }
      });
    </script>

这会抛出 ExecJS::RuntimeError

从视图中移除标签并将代码放在 app/assets/javascripts/post.js.coffee 中

$("#forward_date").change(function() {
  if($(this).is(":checked")) {
    $("#post_date").show("slow");
  } else {
    $("#post_date").hide("slow");
  } 
});

【问题讨论】:

    标签: jquery ruby-on-rails-3.1 coffeescript


    【解决方案1】:

    咖啡脚本不是咖啡脚本

    应该是:

    $("#forward_date").change ->
      if $(this).is(":checked")
        $("#post_date").show "slow"
      else
        $("#post_date").hide "slow"
    

    【讨论】:

      【解决方案2】:

      这不是你在 Coffeescript 中声明函数的方式。代替关键字function 使用-&gt;

      $("#forward_date").change -> 
        if $(this).is ":checked"  
          $("#post_date").show "slow"
        else
          $("#post_date").hide "slow"
      

      【讨论】:

        猜你喜欢
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-03
        • 1970-01-01
        • 2017-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多