CoffeeScript for Beginners (Part 2 of 2)

by Dan DeMeyere - @dandemeyere

My first post on CoffeeScript was primarily focused on getting CoffeeScript installed and having Node.js continuously compile your .coffee files. I touched on creating simple objects and iterating in a for loop, but this post will be all about the standard .click() handler and AJAX function (as well as some nice tricks).

Click Handlers

The .click() handler is probably the most used jQuery method and it happens to be an easy implementation in CoffeeScript. For the rest of this post, let's assume you have a JavaScript file ( with a .setup() method that is called on page load. So somewhere in your view (after you have included the compiled JavaScript file), you have something that looks like this:

That code will ensure your app.setup() method is called after the DOM has loaded and your JavaScript is aware of every element. So what does your .click() method look like? Like this:


AJAX, which stands for asynchronous JavaScript and XML, has become a staple for Front-end engineers. Anytime you want to talk to a database or load some foreign information without refreshing the page, you'll turn to AJAX. So for the sake of our example, let's say you want to make an AJAX call when someone clicks on a button. I'll assume you know what the JavaScript equivalent is and I'll only show the CoffeeScript:

Going the Extra Mile

There are certain best practices that can help deliver the best and most responsive experience to your users. There are two things in particular I like to do when I have a button that triggers an AJAX call.

The first thing is adding a disabled state when someone clicks the button. The user may not notice the activity spinner in the browser's tab so having a different button design that indicates a change will let the user know that the website is responding to your click. It will also give us a flag to determine if the button has been clicked so we don't make more than one AJAX request if they double click it. Keeping all this in mind, here is what the click handler looks like now:

This does 2 things. The preventDefault() call is there in case you have a valid href attribute on the anchor tag. This will prevent the link from executing. The second thing in here is adding the class 'selected' to the button and then surrounding the AJAX method call with a .hasClass check to make sure the 'selected' class hasn't been added already.

The other thing I like to do is handle the data response from the AJAX call. If something goes wrong in your controller (I'm assuming you're using a MVC framework), but all of the code executes anyways, your JavaScript is unaware that something went wrong and you'll never enter the 'error' block of your AJAX call. This why I always set an error flag in my controller that I pass back. Here is the block of code you'll need in your controller to respond to a AJAX call.

Now that our controller is passing back whether an error occurred or not, our JavaScript can handle accordingly. Here is everything coming together:

Useful Resources

Getting Started with CoffeeScript (Part 1 of 2)

by Dan DeMeyere - @dandemeyere

If you're a Rails developer, CoffeeScript is something you need to pay attention to. With the news that CoffeeScript will be included by default in Rails 3.1, CoffeeScript is definitely generating a sizable amount of momentum and the core Rails team believes it's the future. Knowing this, I was looking for an opportunity to use it and a clean project presented itself this sprint at thredUP. So with the help of my colleagues Kylie and Chris, we dove in and started playing away.

The first step is installing CoffeeScript. I used CoffeeScript's official installation instructions, but I ran into some weird export PATH environment issues so I installed it with Homebrew instead.

To install Homebrew, just run this command in your terminal (assuming you have xCode installed already):

Next, you need to install Node.js, which will compile your CoffeeScript for you. With Homebrew installed, all it takes is one line:

You're almost there. Just two more install commands left. The first is installing Node Package Manager and the second is using NPM to install CoffeeScript.

Done! Pretty harmless, heh? Time to start writing some CoffeeScript! Since people abbreviate JavaScript as JS and I'm a sucker for typing less, I'll just refer to CoffeeScript as CS throughout the rest of this post. It doesn't matter where you place your CS files, but I believe Chris told me the best convention is in your app/assets folder. So if you haven't done that, go into your terminal and make the directory:

You can end your CS files with .coffee or, so create a new file in there so we can finally write some code. The project I'll be using as my example is heavily focused with DOM manipulation and since thredUP's library of choice for that is jQuery, you'll be seeing a lot of that in here.

When I first got everything setup, I was a little bit paralyzed. I didn't know where to even start. So the first thing I did was I wrote what I wanted in code in plain JS:

It's basically a setup function that calls another function which iterates over an array and logs the contents. What does this look like in CS? Like this:

Pretty sexy, right? CoffeeScript is very clean (based on Ruby and Python syntax) and it makes it much easier to work with, to read, and it's easier on the eyes. Before I get ahead of myself, there's a couple of things in this code that need to be explained, but first let's give you some resources. Syntax reference for CS can be found here. Once you're on that website, click 'Try CoffeeScript' and an interactive window appears which allows you to type CS directly into a console that the website compiles the corresponding JS right in front of you. This is what it looks like when I typed in the code above on their console:

The first thing you're going to notice is the JS code that I original wrote and attempted to create is different from what was outputted on their console. The reason is because CoffeeScript's compiler is a better JavaScript programmer than me :) I can assure you that my original block of JS code and the compiled CoffeeScript JS code execute the same, but the CS version is going to do it a lot smarter and probably more efficient. CS is going to compile into the best JS it can without changing how your JS functions.

Another note worth mentioning is that the marketDemand object is oriented off of the JavaScript 'window' object. I didn't know this, but apparently this is something I should have always been doing as it prevents objects, variables, and functions that you write from spaghetti scoping out of control. I think it's one of those "trust me, it's better practice this way and you don't want to discover first-hand why it's necessary, but it is" things.

So let's paste that code into the .coffee file you created. The next step is to compile it on your terminal:

If you paste that into your terminal, it will compile all CS files in your app/assets/coffeescripts folder (-c stands for compile) and output them into your public/javascripts/coffeescripts/ folder (-o stands for output). Now, if you're always looking for short-cuts like I am, you'll like this next one:

That command will watch a specific CS file and when it detects a change, it will automatically re-compile it for you. Pretty killer, right?

This post became a lot longer than I originally intended so I broke it into two posts and I'll post the second one in a couple of days. In the next post I'll be going through using jQuery in CoffeeScript and covering if/else statements and other standard snippets of JS -> CS that you might find handy.