A Shiny New Me

  • Archive
  • RSS

A CoffeeScript Revealing Module

This past week I had the pleasure - and it was a pleasure - to visit the fine city of Sandusky, Ohio. Now up until this point, all I’ve known about Sandusky is this…

We were at the Kalahari Resort for CodeMash. This is a fabulous place by the way. Not only is it a fantastic indoor water park, but they have several restaurants, a wicked awesome candy shop and an arcade that will blow your mind. And your wallet.

CodeMash itself was epic. Unfortunately, being at an indoor water park does not mean you actually get to GO there. We spent almost all of our time at the conference, and since I was actually helping to proctor the event, I stayed pretty busy and didn’t get to attend many sessions.

I did make it to one session though that had a major impact on me.

Brandon Satrom did “CoffeeScript Is For Closers”.  Brandon recorded a version prior to CodeMash and you can find the video here.  I highly recommend watching it.  The session is outstanding.  

I had tried CoffeeScript in the past and found it frustrating.  I found it frustrating for a couple of reasons.

1. How exactly do you use it with your project?

I get it.  It’s a small language that compiles to JavaScript.  It removes curly braces and semicolons.  Great.  Now how do I get it into Visual Studio or my Rails project?  I had tried some third party plugins which I found disappointing because I couldn’t figure out how to use them.

2. My favorite patterns aren’t working anymore

I tend to develop using the same sort of JavaScript patterns over and over again.  These patterns essentially stopped working with CoffeeScript because I couldn’t figure out how to structure them.  No matter what I did, I couldn’t get CoffeeScript to write the JavaScript that I wanted.  So I figured, why not just write the JavaScript myself?

#1 SOLVED

If you have this problem, watch Brandon’s video as he will show you what to do.  That’s not the point of this post.

#2 WAT

What I learned about CoffeeScript is that it enforces some JavaScript best practices on you.  If you aren’t prepared for this, it can be just a tad bit confusing.  When I got home, I gave CoffeeScript another try and here is what I learned about how to recreate my favorite pattern in JavaScript, which is the Revealing Module.

Revealing Module

This is my absolute favorite way to structure my applications.  The idea here is that you declare a variable which you set to a function.  That function returns a variable which has methods.  Each of these methods is public.  Any functions not returned on that variable are private.

Let’s take a look at a sample revealing module.

JavaScript

This simple module is a logger.  When it is intialized, I pass in a jQuery object representing the DOM element on the page where I want content to be logged.  The init() and log() functions are public.  The write() function which actually does the work, is not.

Additionally, I pass in the jQuery library to the main function and set that to $.  It’s a good idea to not just assume that $ is always jQuery.  But it should be.

CoffeeScript

My first run at this with CoffeeScript was a disaster.  This is what I did…(CoffeeScript is on the left and JavaScript is on the right)

There is so much wrong with this, I just don’t know where to start.

Let’s start with the fact that when you run this, pub is undefined.  What? I thought in CoffeeScript you just started rocking with variables without having to declare anything.

Yes, but in this case that you are referencing a variable on a variable that does not exist, you need to first define the variable.  Ok, I can do that…

Now pub is defined, but if you look at the JavaScript that’s getting generated, the last thing returned is the Write function. That’s the ONLY thing I don’t want returned. You can see how this gets frustrating.

To fix this you can just return pub - or if you want, just type the word pub. CoffeeScript returns the last thing by default. Fine, pub.

Best Practices. Pffffftttt.

Now the right thing is being returned out of the function. But here comes the “Best Pratices”.

Normally, we would reference this logger variable as logger.init() and then logger.write(). After we have loaded the JavaScript file, it should be available. But it’s not. Why not?

Notice that CoffeeScript is enclosing this whole variable logger in an anonymous function. It then executes call(this). What this basically does is protect the global namespace, and make sure that this = this. It can be tricky to keep up with exactly what this is equal to in JavaScript because it may be changing with the current scope.  CoffeeScript is ensuring that this is in fact the global this when the function executes.

This is where I learned an important lesson. CoffeeScript protects the global namespace at all costs. It’s basically saying “You’re mom doesn’t live here. Don’t leave your crap lying around”. In “JavaScript, The Good Parts”, Crockford recommends prefixing variables that are going to go onto the global namespace with something like MYAPP. I don’t like that, but the point is that you aren’t just shoving things that could overwrite each other onto the global scope.  CoffeeScript is protecting the global namespace by wrapping my variable declaration in a closure.  As soon as the function is exited, it’s no longer available.

Now that we have talked about why you shouldn’t put things in the global namespace, let me show you how to put something in the global namespace. 

Let’s take a page right out of Jeremey Ashkenas own playbook. He wrote CoffeeScript btw.

Having a look at Underscore.coffee, you can see that the first thing he does is assign root to this. Then, he assigns his underscore variable to the root. This makes the _, and all of it’s functions available off the global namespace.

Passing in jQuery becomes different as well.  Since the whole thing is wrapped in an anonymous function, we don’t need to pass in jQuery like we would with JavaScript.  Instead, we can use the CoffeeScript do, which will create a closure around the logger function, allowing us to pass in jQuery there. 

Here is what the revealing module looks like all finished.

Now that I know what CoffeeScript is going to do, I’m much more inclined to use it. I’m actually looking forward to using it because it makes code much easier to read. Go look at underscore.coffee and see how easy it is to follow. It’s brilliant how this works really. Not only does it compile down to JavaScript, but it teaches you quite a bit about JavaScript in the process.

A special thanks to Dan Mohl who gave me input on this article and contributed to some of the content, including cleaning up the final example.

EDIT

This is what I love about blogging.  Steve Howell provided us with a super sexy and more terse example in this gist from his comment below.  Thanks Steve!

  • 1 month ago
  • 1
  • Comments
  • Permalink
  • Share
    Tweet

1 Notes/ Hide

  1. theprivileges reblogged this from burkeholland and added:
    had after watching Brandon Satrom’s presentation.
  2. burkeholland posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

Portrait/Logo

I am Burke Holland. I am an Evangelist For Kendo UI. I built Instasharp. I live in Nashville. Click here to contact me.

I'm All Over The Interwebs

  • @burkeholland on Twitter
  • Facebook Profile
  • burkeholland on Youtube
  • burkeholland on Grooveshark
  • burkeholland on Foursquare
  • Google
  • My Skype Info
  • burkeholland on github

Twitter

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr