【问题标题】:Why are my coffeescript functions not available from my HTML code ?为什么我的 HTML 代码无法使用我的咖啡脚本功能?
【发布时间】:2013-07-12 22:45:36
【问题描述】:

我在我的 rails 3.2.6 项目中使用 rails-backbone、coffeescript gems。

square = (x) -> x * x alert square(5)

这是它生成的 blog.js.coffee 脚本文件:

(function() { var square; square = function(x) {return x * x;}; alert(square(5));

我需要在另一个视图文件中调用square() 方法。

我怎么称呼它? 我做错了什么吗?

【问题讨论】:

    标签: ruby-on-rails-3 scope coffeescript iced-coffeescript coffeescript-resources


    【解决方案1】:

    您在 Coffeescript 中的所有代码都将在一个自调用匿名函数中。

    要在文件外调用它,只需写:

    window.square = (x) -> x * x 
    

    alert(square(5)) 在另一个函数中

    不过度使用 window 的最佳方法是使用包含所有变量的 App 对象。

    window.App={}
    window.App.square=  (x) -> x * x 
    

    然后alert(App.square(5))

    【讨论】:

    • 什么是自匿名函数?
    • 自调用匿名函数是一个没有名称(因此是匿名)并调用自身的函数。它用于保护代码不被函数外部访问。这是一个关于此的具体问题。
    【解决方案2】:

    像普通的 JavaScript 函数一样调用它:

    <script>    
      square(5)
    </script>
    

    【讨论】:

    • 这不起作用,因为范围内没有square 函数。
    猜你喜欢
    • 2013-09-08
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多