Dec 5, 2012

Ember.js and CoffeeScript

Of all my favorite things about CoffeeScript, one of the less obvious is the way it has encouraged and inspired people to write their own AltJS languages. Naturally, many of these build upon CoffeeScript itself, in some cases extending it with just a feature or two. One well-known example is IcedCoffeeScript, but there are many others.

This week I came across one that I feel is worth a special mention: EmberScript, an extension of CoffeeScript created by Gordon Hempton, who blogs regularly about Ember.js.

I've been floating the idea of writing a book teaching Ember.js in CoffeeScript on the same interactive platform as my Backbone + CoffeeScript book. But it hadn't occurred to me to extend CoffeeScript for a better fit with Ember.js. I wrote Gordon to ask how he got the idea, and this was his reply:

As far as EmberScript is concerned, the idea started with an interest in Ember.js itself. Ember.js is divided into multiple modules, including what is essentially its own javascript-based object model and language runtime. I have also always been a big fan of CoffeeScript, but CoffeeScript has never been a perfect fit with Ember (e.g. CoffeeScript also has its notion of classes). EmberScript is an attempt to give Ember.js constructs first-class language support. Things like property bindings, observers, classes, and mixins are all supported directly within the language itself. Because EmberScript is also a compiled language, really cool things like property dependency inference are also possible! EmberScript is ember-infused CoffeeScript.

You can read more about how Gordon modified the CoffeeScript Redux compiler in his blog post.

Is this the first time a programming language has been forked to support the features of an application framework? Like everything else, I suspect it's been done before. Please leave a comment if you have an example.

Oct 23, 2012

CoffeeScript 1.4.0 Released, No Sign of Source Maps

CoffeeScript 1.4 has arrived! There is not a whole lot to get excited about unless you're using CoffeeScript with Node.js and are tired of deprecation warnings. You can compare the new version with 1.3.3 on this GitHub compare view.

After writing about source maps for CoffeeScript back in April 2012, I felt fairly sure that the 1.4 release would usher in a new era of easier debugging for CoffeeScript. It will certainly come.

Meanwhile, the change log for 1.4.0 on the official CoffeeScript site looks like this:

  • The CoffeeScript compiler now strips Microsoft's UTF-8 BOM if it exists, allowing you to compile BOM-borked source files.
  • Fix Node/compiler deprecation warnings by removing registerExtension, and moving from path.exists to fs.exists.
  • Small tweaks to splat compilation, backticks, slicing, and the error for duplicate keys in object literals.

Aug 29, 2012

CoffeeScript and jQuery

The CoffeeScript project page is overflowing with great examples of the little language used in a clean, uncluttered, academic context. However, when you're ready to see how CoffeeScript works with jQuery, where do you go? Here is a list of blog post, tutorials, and code examples showing the two together, in rough order of difficulty.

I hope that after completing a tour of these posts you agree with Alex MacCaw's words in The Little Book on CoffeeScript: "Using CoffeeScript with jQuery is especially elegant."

Jun 21, 2012

Backbone.js Tutorials in CoffeeScript

Backbone.js and CoffeeScript are a great match. I'm so excited about using them together that I'm writing an online book that teaches Backbone.js in CoffeeScript. It is hardly a unique idea: There are a many people writing blog posts, tutorials, and even screencasts about Backbone.js with the examples in CoffeeScript.

I have a list of these resources that I've been intending to publish since quite a while. It just has this tendency to keep growing longer!

Entries are listed in my best effort at reverse chronological order, from newest (top) to oldest (bottom):

No doubt I have missed a few, and I am certain there will more to come. If you would like me to update this post with your tutorial/screencast/example, please link to it in a comment, with the publication date if it's not prominently displayed.

 (For a wider list of Backbone resources, see the Backbone project wiki.) 

May 8, 2012

CoffeeScript Style Guide

You may have come across the GitHub JavaScript Styleguide, which tells us to:
"Write new JS in CoffeeScript." 
That alone is an awesome endorsement of the "little language", but there is more good advice:
"Follow @jashkenas's style. See the documentation for good examples." 
Without doubt, this is correct. The CoffeeScript home page should be your first stop for style. However, it's not strictly a style guide, so for a more dedicated resource I recommend polarmobile/coffeescript-style-guide. It answers questions such as "tabs or spaces?", and I expect it will continue to grow, becoming a very comprehensive resource.

Of course, you could argue that in the age of computer automation, the best style guides are linters. CoffeeLint is described as "a style checker that helps keep CoffeeScript code clean and consistent." For style consistency across a team, it's likely to be a great choice.

Finally, as an example of good CoffeeScript style in the context of hairy, real-world programming, Jeremy Ashkenas recommends the source code for the Pow server.

This list is by no means complete and is open for your contributions. Where do you go for great CoffeeScript style?

Apr 30, 2012

The CoffeeScript Compiler

The CoffeeScript compiler is written in what? CoffeeScript?

I just love this recent exchange on the #coffeescript IRC channel between CoffeeScript creator Jeremy Ashkenas and an unnamed visitor.

13:14 S: Hi, I have just a little question : In what language is written CoffeScript ? (I have see the GitHub but... I don't see a answer)
13:17 S: In src/ they have some .coffee script but CoffeeScript can be write in CoffeeScript :D
13:18 jashkenas: yes, yes it can.
13:18 jashkenas: It's written in CoffeeScript.
13:18 S: What ? I don't understand...
13:19 jashkenas: It was originally written in Ruby.
13:19 S: CoffeeScript can't be compileted by itselft ...
13:19 jashkenas: When that version of the compiler was complete enough.
13:19 jashkenas: It was ported over to CoffeeScript
13:19 S: Ok, I understand
13:20 jashkenas: Then that CoffeeScript source was passed through the Ruby compiler, producing JavaScript
13:20 jashkenas: Then that JavaScript recompiled the CoffeeScript
13:20 jashkenas: and now it recompiles itself.
13:20 S: Ok, nice :D
13:20 S: I little strange but why not :D
13:21 S: And by the way thx jashkenas for this :D I Love ! <3
13:21 jashkenas: cheers.

Meanwhile, Make a Better CoffeeScript Compiler on Kickstarter just reached its goal of $12,000, making it possible for heavyweight committer Michael Ficarra to devote four months of full-time work to the project.

If you haven't noticed, we appear to be entering a new era of fan-supported open-source software (OSS) development projects. The first such project to catch my attention was Yehuda Katz's, which is currently funded at almost 2x its initial goal. I think this is a welcome and healthy turn of events for open source, and will result in an explosion of activity as more and more contributors find it possible to carve out serious time without needing to reach the threshold of full-time, salaried employment with a corporate sponsor.

Apr 13, 2012

CoffeeScript Gets Strict Mode

What's strict mode? And more importantly, how does it work in CoffeeScript 1.3.x?

Mozilla Developer Network (MDN) defines ECMAScript 5 strict mode as "a way to opt in to a restricted variant of JavaScript." It basically provides a syntax error system to prevent you from creating trouble with JavaScript in a number of areas, ranging from the commonplace (global variable leaks) to the arcane (numeric octal literals). It also signals security issues. For further reading about strict mode and JavaScript, check out John Resig's post on strict mode.

CoffeeScript already does quite a bit to guard us from JavaScript pitfalls, so what additional help do we get from strict mode? Alex MacCaw has written this up nicely in the "Strict mode" section of The Little Book on CoffeeScript, Chapter 7, The Bad Parts.

For the final word on the feature, read the CoffeeScript project issue on GitHub. Jeremy Ashkenas' comment on the issue is noteworthy: "I think if we do this, we enforce our static strict mode restrictions everywhere, but we do not put any "use strict"directives into your code for you." In other words, the CoffeeScript compiler does the strict mode syntax checks itself, at compile time. This is good. You don't want to wait until you run the generated JavaScript output to discover your errors. 

Apr 3, 2012

Source Maps for CoffeeScript

One of the more serious concerns about CoffeeScript is that it lacks a first-class debugging environment. The code that you see in a browser debugger is the compiled JavaScript, not the CoffeeScript source. Thanks to JavaScript Source Maps, however, this long-running issue will likely be solved in the very near future.

JavaScript Source Maps is a system of references from JavaScript executing in the browser to original source files that have been minified, concatenated, compiled, or otherwise transformed. Chrome dev tools evangelist Paul Irish called Source Maps "the biggest thing to happen to JavaScript debugging in years." The Google Chrome team is pushing aggressively toward the release of Source Maps support (you can preview the feature in Chrome Canary).

You can read more about Source Maps in MozillaWiki feature page, in this tutorial, and in the formal proposal co-authored by Mozilla and Google. There is a Source map support plan discussion on the CoffeeScript Google Group.

Finally, Mozilla intern Nick Fitzgerald has produced a great what-I-did-this-summer video explaining the importance of Source Maps and of languages such as CoffeeScript. I recommend watching all 15 minutes of it, but for the TL;DR crowd, start around minute 11 for the sequence in which he demos an actual JavaScript console error with a link back to CoffeeScript source. Woo Hoo!

Update (2012/4/13)
Now that CoffeeScript 1.3 has shipped, Jeremy Ashkenas says that Source Maps support will be the focus of the next release of CoffeeScript. One comment on the announcment reads: 
"Source maps in Firefox and Chrome will be one of the most important pieces of software infrastructure since Javascript itself. It will be the realization of Stallman's 'one script to unite them all' vision for GNU GUILE from the 'Tcl wars.' A pity that it isn't Lisp, but there is enough goodness in Javascript (and Coffeescript) to make me very optimistic." 
Hyperbole? We'll see.

Update (2013/3/5)
Almost a year after my original post, CoffeeScript 1.6.1 now supports Source Maps via the --map compiler option!

Mar 20, 2012

BackboneConf Schedule Includes Ember.js and Knockout.js

The lineup for the first BackboneConf has been released, and delivering on an implicit promise made in the call for papers, the schedule includes presentations on alternative JavaScript MV* projects: Ember.js will be covered by Yehuda Katz, and Knockout.js by creator Steven Sanderson. It would be amazing if someone could get these two to engage in dialogue contrasting Ember and Knockout, which seem more similar than they are different in their value proposition of data binding with support for computed properties. If you attend BackboneConf, do not miss that particular hallway conversation.

At a reasonable $349, the two-day, single-track conference is a very welcome addition to the growing JavaScript conference scene. The May 30, 2012 keynote will be delivered by Jeremy Ashkenas, creator of both Backbone and CoffeeScript. Sadly, CoffeeScript is nowhere to be seen on the BackboneConf schedule. But if you're wondering, we at CoffeeScript Love can tell you: Writing your Backbone applications in CoffeeScript is a great way to go.

Mar 8, 2012

Testing CoffeeScript in Rails

As I mentioned in an earlier post on testing CoffeeScript in Node.js, Mocha is a flexible and feature-rich test framework for JavaScript. It is elegant, powerful, and a joy to use. But how do you use Mocha with Rails? Faced with this obstacle, I created MochaRails.

MochaRails is a mountable Rails engine that serves a browser-based Mocha test suite, along with your development JavaScript files, via the Asset Pipeline. It loads Chai for both should- and expect-style assertions, although since Mocha is decoupled from the assertion library, you can use another assertion library if you choose (or even write your own.)

Using should-style assertions and CoffeeScript, Mocha tests are the best-looking implementation of BDD that I have ever seen in any language. For example, here are some simple tests for a Backbone.js View.

describe 'ItemView', ->

  before ->
    @itemView = new Backbone.View
      tagName: 'li'
      className: 'item'

  describe "el", ->

    it 'should return a value', ->

    it "should return an 'li' element", ->
      @itemView.el.tagName.should.equal "LI"

  describe '$el', ->

    it "should have class 'item'", ->

I would argue that even if you can't or don't want to write your production code in CoffeeScript, you should write your tests in CoffeeScript. By eliminating so much visual noise, CoffeeScripts syntax helps bring the goal of BDD--specs that anyone can read to understand the intended behavior of your system--so much closer to reality.

Once you've installed MochaRails and added the test above (simple to do, and explained in the project's Readme), open localhost:3000/mocha to execute your test suite. If you've never seen Mocha's clean and elegant report for browser tests, prepare to be impressed.

Now that's clean! It may seem almost too clean with just three tests, but once you have scores of contexts and hundreds of tests, you'll appreciate the aesthetic. Errors are colored red of course, but Mocha errors do not light up the page like a garish billboard.

Mocha also supports asynchronous code with a simple callback mechanism. I highly recommend you browse Mocha's features and give MochaRails a try.

Update: Since I first looked into using Mocha with Rails, a project very similar to MochaRails has appeared: Konacha. It looks like momentum is building behind Mocha and Chai!

Feb 23, 2012

Interactive CoffeeScript Books

If you own an iPad and enjoy the format of the interactive HTML book Smooth CoffeeScript, you might take a look at CoffeeScript: An Interactive Reference by Trevor Burnham. At just 15 pages, it is priced at $4.99. The thing that excites me is that it encourages you to code while you read.

In my mind, there is no good reason why every digital book on JavaScript programming should not be interactive. Typically, programming books make their example source code available for download, or somewhat better, cloning from GitHub. I usually do this and keep the code open in an editing environment while reading. When the code fragment I am studying is not too difficult to locate (mostly the case), as well as not too difficult to execute (sadly, not often the case), I love to do so, at a minimum just to see that it actually works. Often I go beyond just running the example and get into some experimentation, leading to much deeper learning. I do all of my technical reading on an 11" MacBook Air in order to lower the barrier to "coding along with the text" as much as possible.

For my upcoming book on Backbone.js and CoffeeScript, I am working on a subtle approach to interactivity that does not disrupt the flow of normal reading. Most readers say that they do not even notice at first that the code listings are embedded CoffeeScript editors. You can experience a prototype in this tutorial on helper functions with Eco (Embedded CoffeeScript templates). The current version of the format now uses wonderfully readable assertions from chai.js instead of browser alerts.

Please let me know what you think. Does interactivity in HTML books outweigh the disadvantages of reading in a browser? What do you think of iBooks? Any thoughts about executable JavaScript in PDF or other digital formats?

Feb 15, 2012

Backbone and Ember with Ashkenas and Katz

The team at the JavaScript Jabber podcast have really pulled together an amazing show this week, bringing Jeremy Ashkenas and Yehuda Katz together for a riveting live discussion of Backbone.js and Ember.js. This is a fantastic followup to the IRC discussion about Backbone and Ember that I covered on CoffeeScript Love a couple weeks ago.

In the 54-minute podcast, Katz talks at length about the design philosophy behind Ember, as well as the lessons he learned about convention over configuration while working on jQuery and Merb. He also talks about "the pipe dream" of using the same Mustache.js templates on both client and server. But don't assume it's just Katz lecturing (which I will listen to any day, by the way.) With Ashkenas and four other panelists on the line, the discourse is multi-sided, rapid, and forceful. Admittedly, there isn't much about CoffeeScript. But if you follow trends in JavaScript, these are the guys shaping the future, engaged in frank conversation. You shouldn't miss it.

Feb 9, 2012

Testing CoffeeScript with Mocha

Mocha is a flexible and feature-rich test framework for JavaScript created by the insanely prolific open-source developer TJ Holowaychuk. It's used to test some prominent projects in the Node.js ecosystem, including Connect and Express.

If you already have CoffeeScript installed (you do, don't you!? if not get it now), giving Mocha a try couldn't be easier. The clean, elegant look of nested callback functions in CoffeeScript, combined with Holowaychuk's awesome Should assertions, make CoffeeScript + Mocha the best-looking implementation of BDD that I have ever seen. Now, good looks aren't everything, but if they make you want to write a lot more tests, they can't be bad. (A word of caution: While Mocha works beautifully in the browser, Should does not, so for browser tests you'll need to use an alternate assertion library, such as Expect. Update: Chai provides an implementation of should assertions that works in the browser.)

Enough talk, let's look at a simple Mocha test in the BDD style.

describe 'Array', ->
  describe '#indexOf()', ->
    it 'should return -1 when not present', ->
      [1,2,3].indexOf(4).should.equal -1

Here is how to run the example:
  1. Install Mocha (globally for convenience): $ sudo npm install -g mocha should
  2. Copy the code above to
  3. $ mocha --require should
As you can see, Mocha can compile and execute CoffeeScript directly when run in Node.js (browser usage requires compilation to JavaScript.) Even your production files can be in CoffeeScript. I created a simple mocha-coffeescript-boilerplate project on GitHub to illustrate this and get you started.

Coming soon on CoffeeScript Love: How to integrate Mocha browser tests with the Rails (>= 3.1) Asset Pipeline. Update: Read Testing CoffeeScript in Rails.

Feb 3, 2012

Backbone.js vs Ember.js

In the #documentcloud IRC channel on January 31, 2012, Jeremy Ashkenas (jashkenas) and Yehuda Katz (wycats) were asked by Travis Swicegood to contrast Backbone.js and Ember.js. (I have removed some IRC noise and unrelated conversations for clarity.)

09:56 tswicegood: so here's a loaded question since both of you are here...
09:56 tswicegood: what's the main differences between the backbone and ember?
09:56 tswicegood: I have some ideas, but I'm curious to hear from your perspectives :-)
09:58 wycats: tswicegood: Ember focuses heavily on bindings as the core abstraction, backbone focuses on raw events
09:58 wycats: Ember supports events
09:58 jashkenas: tswicegood: as with all of this stuff -- very different approaches to the same thing: building JS apps.
09:58 wycats: but Ember users tend to prefer bindings
09:58 wycats: jashkenas: does ^ seem correct?
09:58 jashkenas: eh, I think there's more than just that ;)
09:59 wycats: :p
09:59 jashkenas: from a user's perspective.
09:59 wycats: tswicegood: also, Ember's scope is larger -- for instance, we have a bundled template engine that is binding-aware
09:59 wycats: backbone is template-engine agnostic
10:01 jashkenas: tswicegood: but how to put it concisely ... Ember is an (IMO) more experimental attack at the end-to-end problem, by introducing new concepts to JavaScript, like the aforementioned Ember.meta bindings on objects ... Backbone is simply the lowest-common denominator set of functions and patterns to be productive.
This small discussion hardly scratches the surface in assessing either of these excellent JavaScript application frameworks. To make an informed decision about which to use in your own projects, you should: a) try them for yourself, b) read their source code, c) review their real-world adoption, and d) learn more about the philosophy and commitment of their core teams.

Update: Jeremy Ashkenas has published a much longer portion of the conversation about Backbone and Ember that continued on IRC. Also, the February 13, 2012 episode of JavaScript Jabber brought Ashkenas and Katz together for a live discussion on Backbone and Ember.

Jan 31, 2012

CoffeeScript Love Selected as DZone MVB

CoffeeScript Love has been chosen for DZone's MVB (Most Valuable Blogger) program! Yes, I know the name says Blogger not Blog, but let's be honest: As happy as I am to see my picture in a grid with Martin Fowler, all the props go to the real hero, the "little language."

The editors at DZone have clearly figured out what we already know, namely that CoffeeScript is seriously great. Hopefully, syndication of this blog will help CoffeeScript build even more momentum. Congrats, CoffeeScript!

Jan 30, 2012

CoffeeScript in Basecamp Next

37Signals published details today about the next generation of its flagship Basecamp product, with impressive statistics revealing that its codebase is almost as much CoffeeScript as Ruby. Astonishingly, this seems not to be even as high a percentage as it might be. DHH (David Heinemeier Hansson, creator of Ruby on Rails) says in the post's comments that he is not a heavy user of client-side MVC frameworks such as Backbone.js:
I still don’t like client-side MVC from a developer’s standpoint, which is why - comparably speaking - there’s only a tiny amount of it in Basecamp Next. But there are indeed places where it makes a lot of sense, such as a calendar, for example.
 He also reveals that the vast majority of view rendering is still server-side Ruby:
... we use Eco for our client-side templates, but we only have 24 of those versus hundreds of regular ERB templates. Half the client-side templates relate to our new calendar.
Very interesting stuff. CoffeeScript Love can't wait to hear more about CoffeeScript and the internals of Basecamp Next.

Jan 24, 2012

"I Never Want to Write Plain JavaScript Again"

These are the words of legendary open-source JavaScript developer Sam Stephenson in a recent talk on CoffeeScript at FOWA 2011. The 45-minute presentation (video is here, slides are here) chronicles the evolution of higher-level approaches to JavaScript, including GWT, Pyjamas, Objective-J, and finally CoffeeScript. If you've been on the fence with CoffeeScript, this could be the one to tip you. If you're just learning CoffeeScript, it is a great, thoughtful, well-paced introduction to the language. Sam structures the rest of the talk around "10 Things I Love About CoffeeScript."

Here are Sam's top ten favorite things about CoffeeScript:

  1. Function Syntax
  2. Significant Whitespace
  3. Bare Objects
  4. Everything's an Expression
  5. Comprehensions
  6. Classes & Inheritance
  7. Bound Functions
  8. Conditionals
  9. Destructuring Assignment
  10. String Syntax

Jan 15, 2012

Alex MacCaw Interview on The Changelog

Even if you follow Spine.js and Alex MacCaw closely (as I do), this recent interview with him on The Changelog is a good opportunity to hear the backstory on many of his design decisions. He discusses Spine and Backbone, Eco and Mustache, and weighs in on the debate about emulating native look-and-feel in mobile Web apps. Naturally he doesn't fail to mention how much he values CoffeeScript and admires Jeremy Ashkenas. It's fairly short (20 minutes), but definitely worth a listen.

Also at The Changelog is this epic interview with HTML5 Boilerplate creator Paul Irish. I consider it an overflowing grab-bag of goodies for anyone who develops for the browser.

Jan 1, 2012

CodeMirror CoffeeScript Mode

CodeMirror is an open-source, extensible, full-featured code editor library for the browser that supports a number of different languages--including CoffeeScript!

The Underscore.js Reference in the online book Smooth CoffeeScript uses CodeMirror for its interactive code listings. Another nice example is this demo of Calculize in CoffeeScript by Jeff Pickhardt, who created the CoffeeScript mode for CodeMirror.