gpt4 book ai didi

javascript - Coffeescript - 如何在 ruby​​ on rails 中将 javascript 转换为 coffeescript?

转载 作者:行者123 更新时间:2023-11-29 20:47:52 24 4
gpt4 key购买 nike

我在 test.html.erb 的 View 中有一个按钮,如下所示

<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 简写 @ 上全局限定您的函数范围。

来自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)
...

CoffeeScript @ 是 JavaScript 中 this 的简写。因此,在您的示例中,因为您是在顶级窗口范围 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.

关于javascript - Coffeescript - 如何在 ruby​​ on rails 中将 javascript 转换为 coffeescript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53606754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com