Coffeescript - 如何在 rails 上将 javascript 转换为 ruby 中的 coffeescript?

Coffeescript - How to convert a javascript into coffeescript in ruby on rails?

我在test.html.erb的视图中有一个按钮如下

<button  id="Todo_full" onclick="showFullscreen(this);">Full size</button>

及其javascript如下:

    function showFullscreen(event)
    {
    var elem = document.getElementById('card_' + event.id);

        if (elem.requestFullscreen) {
        return elem.requestFullscreen();
        }
        else if (elem.mozRequestFullScreen) 
        {

        /* Firefox */
        return elem.mozRequestFullScreen();
        }
    } 

当我将 javascript 代码保存在 test.html.erb 文件下方时,它工作正常。 当我通过 http://js2.coffee/ 将此代码转换为 coffeescript 并将代码保留在 app/assets/javascript/test.coffee 中时,如下所示:

showFullscreen = (event) ->
  elem = document.getElementById('card_' + event.id)
  if elem.requestFullscreen
    return elem.requestFullscreen()
  else if elem.mozRequestFullScreen

    ### Firefox ###

    return elem.mozRequestFullScreen()
  return

它在控制台中显示错误

Uncaught ReferenceError: showFullscreen is not defined
    at HTMLButtonElement.onclick ((index):384)

即使我在 coffeescript 代码的顶部使用 window.onload = ->,我也会在控制台中遇到同样的错误。

谢谢

您 运行 遇到的问题是 JS 和 CoffeeScript 之间的不同范围。为了让您的代码正常工作,您需要在 window 或 CoffeeScript shorthand @.

上全局限定您的函数范围

来自CoffeeScript docs

If you’d like to create top-level variables for other scripts to use, attach them as properties on window.

你的函数看起来像:

# Using window
window.showFullscreen = (event) ->
  elem = document.getElementById('card_' + event.id)
  ...

# Or using @
@showFullscreen = (event) ->
  elem = document.getElementById('card_' + event.id)
  ...

对于 JavaScript 中的 this,CoffeeScript @ 是 shorthand。因此,在您的示例中,因为您在顶层 window 范围 window == @ 定义函数。请记住 中你的函数范围会有所不同 window != @,而 @ 将被限定在你的 this 中的任何范围内功能。 This blog post has a nice explanation:

Speaking of this, CoffeeScript has a shortcut for it, the @ symbol. It's easy to write this off as meaningless syntactical sugar, but it is useful. First, constructor parameters prefixed with @ are converted into properties:

 # CoffeeScript
 class User
   constructor: (@id) ->
 // JavaScript
 function User(id) {
   this.id = id;
 }

Beyond this though, it's a nice way to define class method:

 # CoffeeScript
 class User
   constructor: (@id) ->

    @findById: (id) =>
    ...
 // JavaScript
 function User(id) {
   this.id = id;
  }
 User.findById = function() {};

Neither @ nor the fat arrow => mean that you don't have to worry about the current meaning of this (or its alias @). They aren't silver bullets, which isn't to say that they don't add value.