Update: My problem was caused by two functions returning and not just one. The callback function in the $.each
loop was generating the returns in the if/else
block. Even though I link it later in the question, there is a good question about how to override returns when CoffeeScript compiles to JavaScript. This is not a duplicate of that question; I had a more specific problem.
I'm trying to learn CoffeeScript for fun by porting some work I did in JavaScript with the jQuery Widget Factory. Assume $foos
is a boolean array. I have a CoffeeScript function that looks similar to this:
$ = jQuery
activateCats = ($foos) ->
$.each $foos, (idx, foo) ->
$bar = $(".cats").eq(idx)
if foo
$bar.addClass("ui-state-active")
.removeClass "ui-state-disabled"
else
$bar.removeClass("ui-state-active")
.addClass "ui-state-disabled"
# add another empty return here
return
The compiled JavaScript looks like this:
var $, doThings;
$ = jQuery;
activateCats = function($foos) { // Function 1
$.each($foos, function(idx, foo) { // Function 2
var $bar;
$bar = $(".cats").eq(idx);
if (foo) {
return $bar.addClass("ui-state-active").removeClass("ui-state-disabled");
} else {
return $bar.removeClass("ui-state-active").addClass("ui-state-disabled");
}
});
};
If I don't include the return at the bottom it compiles to this (note the return in front of my $.each
loop):
var $, doThings;
$ = jQuery;
activateCats = function($foos) {
return $.each($foos, function(idx, foo) {
var $bar;
$bar = $(".cats").eq(idx);
if (foo) {
return $bar.addClass("ui-state-active").removeClass("ui-state-disabled");
} else {
return $bar.removeClass("ui-state-active").addClass("ui-state-disabled");
}
});
};
I'm pretty sure I don't want those returns to be in my $.each
loop. I'm not sure why CoffeeScript is adding them, because I have the empty return
at the bottom of my function. I was having this problem before in other places but I read this thread and solved those issues. I've tried the various methods in that thread and none of them seem to work for this edge case.
How can I prevent CoffeeScript from adding these returns?