**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][1] 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][2]. 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][3] 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?**
[1]: https://stackoverflow.com/questions/7391493/is-there-any-way-to-not-return-something-using-coffeescript
[2]: http://jqueryui.com/widget/
[3]: https://stackoverflow.com/questions/7391493/is-there-any-way-to-not-return-something-using-coffeescript possible duplicate of Is there any way to not return something using CoffeeScript?
以上就是How do I prevent these unwanted returns in my if/else block?的详细内容,更多请关注web前端其它相关文章!