Multiple Functions as Arguments in CoffeeScript [d

2019-02-02 03:27发布

问题:

This question already has an answer here:

  • How to pass two anonymous functions as arguments in CoffeScript? 4 answers

I can't for the life of me figure this out or find a solution online. I am trying to figure out how to write a script in CoffeeScript from jQuery based JavaScript.

The script is this:

jQuery('.post-thumb a').hover( function() {
    jQuery(this).find('.overlay').fadeIn(150);
}, function() {
    jQuery(this).find('.overlay').fadeOut(150);
});

I initially tried rewriting that like this:

thumb_overlay =>
    $('.post-thumb a').hover
        => $(this).find('.overlay').fadeIn(150)
        ,=> $(this).find('.overlay').fadeOut(150)

But that didn't work, so I thought I would post here. So how do I write that JavaScript in CoffeeScript?

回答1:

I think you're almost there but you need some parentheses (to group things) and some backslashes to keep CoffeeScript from misinterpreting the newlines. Try this:

thumb_overlay =>
    $('.post-thumb a').hover \
        (=> $(this).find('.overlay').fadeIn(150)), \
        (=> $(this).find('.overlay').fadeOut(150))

You could also mash it all into one line but you might regret it in a few months:

thumb_overlay =>
    $('.post-thumb a').hover (=> $(this).find('.overlay').fadeIn(150)), (=> $(this).find('.overlay').fadeOut(150))

And BTW, go to the homepage and hit "Try CoffeeScript", that's an easy way to sort small bits of CoffeeScript out; start with the -> version to cut down on the noise in the JavaScript and then switch to => when you get the right JavaScript.

I'm not sure if you want to => forms in this case, the -> form form:

$('.post-thumb a').hover \
    (-> $(this).find('.overlay').fadeIn(150)), \
    (-> $(this).find('.overlay').fadeOut(150))

would give you the the JavaScript that you started with:

$('.post-thumb a').hover((function() {
  return $(this).find('.overlay').fadeIn(150);
}), (function() {
  return $(this).find('.overlay').fadeOut(150);
}));

And if you don't like backslashes, you could do this:

$('.post-thumb a').hover( 
    -> $(this).find('.overlay').fadeIn(150)
    -> $(this).find('.overlay').fadeOut(150)
)

Or if your functions are longer, you could give them names and skip a lot of the problem:

fadeIn  = -> $(this).find('.overlay').fadeIn(150)
fadeOut = -> $(this).find('.overlay').fadeOut(150)
$('.post-thumb a').hover(fadeIn, fadeOut)

I tend to prefer this approach in both JavaScript and CoffeeScript, reads better to me.



回答2:

For those searching for an answer in 2014 CoffeeScript,

$('someSelector').hover ->
  alert "hello"
, ->
  alert "world"

compiles into

$('someSelector').hover(function() {
  return alert("hello");
}, function() {
  return alert("world");
});