![](/img/trans.png)
[英]CoffeeScript - How to work with coffeescript in ruby on rails?
[英]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 速记@
上全局范围内定义您的函数。
如果您想为其他脚本创建顶级变量以供使用,请将它们作为属性附加到
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 != @
,而@
作用域将限定为您函数内的任何this
。 这篇博文有一个很好的解释:
说到
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() {};
@
和粗箭头=>
都不意味着您不必担心this
(或其别名@
)的当前含义。 它们不是灵丹妙药,这并不是说它们不会增加价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.