【问题标题】:coffee scripts doesn't work in my ruby app咖啡脚本在我的 ruby​​ 应用程序中不起作用
【发布时间】:2015-04-07 12:58:57
【问题描述】:

我尝试在我的 ruby​​ 应用程序中添加 js 操作。 我阅读了 Rails 指南中的资产管道和使用 JavaScript,但我无法重现第二个中描述的内容。 我是 Rails 的初学者,所以也许我对文件做了太多的“操作”,还有扩展......

我有

控制器“mycontroller”app/controllers/mycontroller_controller.rb

class mycontrollerController < ApplicationController
    def new
    end
end

application.js 应用程序/资产/javascripts

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

mycontroller.coffee app/assets/javascripts

当我在浏览器中加载应用程序时,资产似乎已正确包含

<script src="/assets/mycontroller-d915d2e33a0815bf7b1ac3c478a90599.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/application-fdae31866ddfa65ac8bed4781fb60a9c.js?body=1" data-turbolinks-track="true"></script>

问题:我必须重命名 .js.coffee 中的 .coffee 文件吗?我试过了,但没有任何改变。

我遵循“在 Rails 中使用 JavaScript”并像这样修改了我的文件:

new.html.erb app/views/mycontroller

<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>

mycontroller.coffee app/assets/javascripts

paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
      element.style.color = textColor

我认为咖啡脚本编译正确:

(function() {
    var paintIt;

        paintIt = function(element, backgroundColor, textColor) {
            element.style.backgroundColor = backgroundColor;
            if (textColor != null) {
                return element.style.color = textColor;
            }
        };

 }).call(this);

但是点击什么也没发生……有什么想法吗?

提前感谢我们的帮助。

【问题讨论】:

  • Google Chrome 的 Javascript 控制台中是否有与 javascript 相关的错误?而且,您的 Rails 应用程序在哪些环境(例如开发、测试或生产环境)上运行?
  • 确实,我有这个错误:Uncaught ReferenceError: paintIt is not defined onclick。否则,我的应用程序在本地服务器上运行,因此我认为是在开发环境中。谢谢。

标签: javascript ruby-on-rails ruby coffeescript


【解决方案1】:

问题在于 CoffeeScript 旨在以“不显眼的方式”与 DOM 通信,因此您不会在 HTML 中看到任何 JS 的迹象。发生这种情况是因为您的脚本被编译为一个自执行匿名函数,它将其范围与全局命名空间隔离开来。 paintIt 不会“泄漏”到外面。这是设计使然(和here's some explaination on this)。你需要以不同的方式做到这一点。

为了区分属性的用途,我个人将任何与行为相关的内容放在data-* 属性中,并在[data-paint] 等选择器上绑定事件,这表明存在此类属性。我建议你像这样重写你的 HTML:

<a href="#" data-paint="#990000">Paint it red</a>

然后为每个data-paint处理click事件:

$("[data-paint]").on "click", ->
    # `@` is basically `this` and `@thing` is `this.thing`
    # `@dataset` contains the data attributes of the given element
    @style.color = @dataset.paint

A-a-然后你就完成了。见the JSFiddle

【讨论】:

  • 我试过了,但在我的情况下不起作用。也许我必须继续我对 ruby​​ 及其概念的一般性学习,稍后我会尝试学习更多的细节点,比如 js 和 coffescripts。感谢您的时间和帮助。
  • 我创建了一个新应用程序,尝试了您的答案并且它有效。因此,尽管我确实做了太多的操作并损坏了我的应用程序。但是,仅当我按住单击时才会应用着色。这对你来说是正常行为吗?谢谢。
  • 不正常,但是用代码写的没有这样的效果。可能是特定于浏览器的。可能与此点击应用于&lt;span&gt;这一事实有关,这不是一个太常用的点击元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
相关资源
最近更新 更多