coffee脚本没有'在我的ruby应用程序中不起作用

coffee scripts doesn't work in my ruby app

本文关键字:ruby 我的 应用程序 不起作用 脚本 coffee      更新时间:2023-09-26

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

我有

控制器"mycontroller"app/controllers/mycontroller_controller.rb

class mycontrollerController < ApplicationController
    def new
    end
end

application.js app/assets/javascripts

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

mycontroller.coffee应用程序/资产/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应用程序/资产/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);

但点击不会发生任何事情。。。知道吗?

提前感谢我们的帮助。

问题是CoffeeScripts旨在以"不引人注目的方式"与DOM通信,这样您就不会在HTML中看到任何JS的迹象。发生这种情况的原因是,您的脚本被编译为自执行匿名函数,该函数将其作用域与全局命名空间隔离。paintIt不会"泄漏"到外部。这是经过设计的(这里有一些解释)。你需要采取不同的做法。

为了区分属性的用途,我个人将任何与行为相关的东西放在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

你完了。请参阅JSFiddle。