【问题标题】:Coffeescript - How to convert a javascript into coffeescript in ruby on rails?Coffeescript - 如何将 javascript 转换为 ruby​​ on rails 中的咖啡脚本?
【发布时间】:2019-05-05 12:20:53
【问题描述】:

我在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)

即使我在咖啡脚本代码的顶部使用window.onload = -&gt;,我也会在控制台中遇到同样的错误。

谢谢

【问题讨论】:

  • 那些代码 sn-ps 并不完全等价。 JavaScript 定义了一个 global showFullscreen 函数,而 CoffeeScript 则在作用域包装器内创建了一个本地 showFullscreen 函数。也许你想说@showFullScreen = (event) -&gt; ...window.showFullScreen = (event) -&gt; ...。或者更好的是,根本不使用onclick 属性,创建本地函数并将它们绑定到元素。

标签: javascript ruby-on-rails ruby coffeescript


【解决方案1】:

您遇到的问题是 JS 和 CoffeeScript 之间的范围不同。要使您的代码正常工作,您需要在 window 或 CoffeeScript 简写 @ 上全局范围内定义您的函数。

来自CoffeeScript docs

如果您想创建顶级变量供其他脚本使用, 将它们作为属性附加到window

你的函数应该是这样的:

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

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

CoffeeScript @ 是 JavaScript 中 this 的简写。因此,在您的示例中,因为您在顶级窗口范围window == @ 定义函数。请记住,你的函数中,作用域是不同的,window != @,而是@ 的作用域是你函数内部的thisThis blog post has a nice explanation:

说到this,CoffeeScript 有一个快捷方式,@ 符号。 很容易把它写成毫无意义的语法糖,但它 很有用。首先,转换以@为前缀的构造函数参数 进入属性:

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

除此之外,这是定义类方法的好方法:

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

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

@ 和胖箭头=&gt; 都不代表你不用担心 this(或其别名 @)的当前含义。他们不是银 子弹,这并不是说它们没有增加价值。

【讨论】:

  • 谢谢老哥的回复,不过我现在已经不做ror技术了。
  • Awww 无赖@shashiverma! RoR 仍然是我的最爱 :-) 如果您认为这个答案还是有帮助的,您能否标记为未来观众的正确答案?出于好奇,您现在使用什么技术?
  • 当然为什么不呢,我在 ror 中创建了一个管理模板,但我总是对管道、CoffeeScript 感到困惑,我们应该按什么顺序导入(或要求)库。现在我正在开发一个 javascript 框架 vuejs。
猜你喜欢
  • 2019-05-02
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 2018-02-03
  • 2012-10-24
  • 1970-01-01
相关资源
最近更新 更多