Rails没有看到简单的Coffeescript

时间:2014-04-10 19:27:33

标签: ruby-on-rails coffeescript

我正在关注关于jquery的http://guides.rubyonrails.org/working_with_javascript_in_rails.html教程 - 我正在尝试运行最简单的事情:

welcome.js.coffee

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

和欢迎索引

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

这也不起作用

<a href="#" onclick="paintIt(this, '#009900', '#FFFFFF')">Paint it green</a>

当我点击它时,颜色不会改变。我做错了什么或我没做什么?

2 个答案:

答案 0 :(得分:0)

我能给出的最好的建议是首先确保调用JS,然后让它不引人注目:

$("a").on "click", (e)->
    e.preventDefault()
    paintIt($(this), $(this).data("background"), $(this).data("foreground"))


<%= link_to "Paint It Red", "#", data: {background: '#990000', foreground: '#ffffff'} %>
<%= link_to "Paint It Green", "#", data: {background: '#009900', foreground: '#ffffff'} %>

答案 1 :(得分:0)

通常,coffeescript输出包含在匿名函数中,以免污染全局命名空间。你的javascript应该是这样的:

(function() {
  var paintIt;

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

}).call(this);

因此它不应该工作 - paintIt属性无法访问onclick变量。您需要将其公开给window对象才能使您的示例正常工作

paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
    element.style.color = textColor
#expose as global
window.paintIt = paintIt

我认为这只是第一步。接下来将使js不引人注目并从coffeescript中设置事件处理程序。然后就没有必要将其暴露为全局。

paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
    element.style.color = textColor
# use DOMContentLoaded or jQuery's: $(document).ready()
document.addEventListener('DOMContentLoaded', ->
  #find <a> tags and setup event listeners
)