如何在 CoffeScript 中传递两个匿名函数作为参数?

发布于 2024-11-17 02:20:29 字数 345 浏览 7 评论 0原文

我想传递两个匿名函数作为 jQuery 悬停的参数,如下所示:

$('element').hover(
  function() {
    // do stuff on mouseover
  },
  function() {
    // do stuff on mouseout
  }
);

只需一个就很容易 - hover -> - 但是 CoffeeScript 中两个函数的正确语法是什么?我尝试了 ...hover ->...hover( ->... 等,但没有任何东西能让我得到上面的结构。

I want to pass two anonymous functions as arguments for jQuery's hover, like so:

$('element').hover(
  function() {
    // do stuff on mouseover
  },
  function() {
    // do stuff on mouseout
  }
);

It's easy with just one – hover -> – but what is the proper syntax in CoffeeScript for two? I tried ...hover ->, ...hover( ->..., etc. but nothing gets me the above structure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

玩物 2024-11-24 02:20:29

我认为问题在于使用单行注释///* .. */ 中包含的单行注释似乎工作正常。这是一个等效的示例,其中包含除注释之外的其他内容。

$('element').hover(
  -> console.log("first")
  -> console.log("second")
)

或者使用 /* .. */ 进行注释。

$('element').hover(
  -> /* first */
  -> /* second */
)

您可以在 尝试 CoffeeScript 选项卡下尝试这些示例。 CoffeeScript 添加了一个 return 语句来返回函数的最后一个表达式。如果您想要不执行任何操作且末尾不包含 return 的简单函数,请尝试:

$('element').hover(
  () ->
  () ->
)
// $('element').hover(function() {}, function() {});

I think the problem lies with using single line comments //. Single-line comments enclosed in /* .. */ seem to work fine. Here's an equivalent example with something other than a comment.

$('element').hover(
  -> console.log("first")
  -> console.log("second")
)

Or with comments using /* .. */.

$('element').hover(
  -> /* first */
  -> /* second */
)

You can try these examples under the Try CoffeeScript tab. CoffeeScript adds a return statement to return the last expression of the function. If you wanted bare-bones functions which do nothing and don't contain a return at the end, try:

$('element').hover(
  () ->
  () ->
)
// $('element').hover(function() {}, function() {});
寄离 2024-11-24 02:20:29

将匿名函数放在括号中。

Put parentheses around the anonymous functions.

命硬 2024-11-24 02:20:29

另一种方法是在调用函数后使用反斜杠,逗号应正确缩进。

$('element').hover \
  -> # do stuff on mouseover
  ,
  -> # do stuff on mouseout

Another way is to use backslash after the caller function, the comma should be indented correctly.

$('element').hover \
  -> # do stuff on mouseover
  ,
  -> # do stuff on mouseout
话少情深 2024-11-24 02:20:29

不带括号或反斜杠

f ->
  0
, ->
  1

1.7.1 上的输出:

f(function() {
  return 0;
}, function() {
  return 1;
});

Without parenthesis or backslash:

f ->
  0
, ->
  1

Output on 1.7.1:

f(function() {
  return 0;
}, function() {
  return 1;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文