Clouds in my CoffeeScript

The "mystery language" CoffeeScript has been around for about 5 years now and I only recently started to play around in it. Like TypeScript, I must add that it's a bit of a learning curve, but once you get the hang of it, it's smooth sailing from there. I've promised myself to keep this short and sweet, so I decided to write an article about calling a Windows Azure Mobile Service (WAMS) from CoffeeScript.

Let's face it, there aren't any smoke and mirrors here. CoffeeScript transcompiles down to JavaScript, like TypeScript does, so calling any REST-based service with the help of your favourite JS framework (in my case JQuery) shouldn't be any different.

In my previous post, I've created a Mobile Service that periodically polls tweets from Twitter and pushes it to a table called 'tweets'. So next, using the power of CoffeeScript, let's build a small sample that reads the tweets from the table and show it on the screen.

In this example, my weapons of choice are:

Here we have simple HTML with references to JQuery, WAMS JS client and a custom script, which is the product of compiled CoffeeScript:

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title></title>
</head>  
<body>  
    <ul id="tweets"></ul>

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mobileservices/MobileServices.Web-1.1.0.min.js"></script>
    <script src="app.min.js"></script>
</body>  
</html>  

The nice thing about Web Essentials is that it supports CoffeeScript out of the box, I’ve just added a file with a ‘.coffee’ extension and we’re good to go. This extension will generate the optimized JavaScript (including a minified version) for us upon save.

The app.coffee script:

url = "https://myservice.azure-mobile.net/"  
key = "sUp3RsEcR3T-k3Y"  
client = new WindowsAzure.MobileServiceClient(url, key)

tweetsTable = client.getTable("tweets")

results = tweetsTable.read().then(  
    (results) -> showTweets(results), 
    (error) -> error(error))

showTweets = (result) ->  
    $.each(result, ->
        $("#tweets").append("<li>" + this.text + "</li>"))

error = (error) ->  
    alert "ERROR: " + error

When we save this, it immediately generates an app.js and app.min.js that we can reference from within the HTML page.

image

Comparing the generated JavaScript to the original CoffeeScript we notice the substantial difference in row count:

image

Till next time!