Writing jQuery in CoffeeScript, further simplifies the syntax. The jQuery(function($)) can be written as jQuery($) -> or simply $ ->.
Take the following example for an instance:
JavaScript
jQuery(function($) {
function changeTab(e) {
e.preventDefault();
$("#tabs li a.active").removeClass("active");
$(this).addClass("active");
$("#tabs ul li a").click(changeTab);
});
Here, the function changeTab(e) becomes changeTab = (e) ->. And you can remove all semicolons and curly brackets. You can also optionally remove parenthesis as well.
CoffeeScript
$ ->
changeTab = (e) ->
e.preventDefault()
$("#tabs li a.active").removeClass "active"
$(this).addClass "active" // or, $(@).addClass "active"
$("#tabs ul li a").click changeTab
Now let's try to convert following jQuery code into CoffeeScript:
JavaScript
function showNumberOfFlights(e) {
var num_flights = $(this).data('flights');
$(this).append("<span>" + num_flights +"`");
$("#tabs span.tooltip").show();
}
CoffeeScript
showNumberOfFlights = (e) ->
num_flights = $(@).data 'flights'
$(@).append "<span>#{flights}`"
$("#tabs span.tooltip").show()