Real Life CoffeeScript
What is CoffeeScript?   CS is a language that compiles into   JavaScript (like HAML and SASS)  Not a superset of JS (not l...
From the makerCoffeeScript is a little language that compiles into JavaScript. Underneath all of thoseembarrassing braces ...
Why all the fuss?CS will be a standard part of Rails 3.1 (along                 with SASS)        It makes JS more like Ru...
Why use CS? compiles to lint-free JS, nothing fancyeasy to write "good parts javascript" that               looks clean  m...
What are the features?Easy variable declaration (lexical scoping)   Easy class inheritance and binding   Easy instance var...
Semantic Shortcuts      -> and => instead of function(){}execute() if that is thing1 and that isnt thing2         and/or/n...
Conditionals if condition? (no parantheses, ? is .nil? not                   .blank?)   if condition?() to evaluate if a f...
How much more?      list traversal: for result in resultsreturn (transform result for result in results)        switch/whe...
Show me some code!
Some ugly JavaScriptvar sortFunction = function(a,b) {    if (typeof(a[sort_col]) === number) {        // numeric sort    ...
class Results    setSort: (col, dir) ->        if col? and dir?            results = _(@results).sortBy (result) -> result...
standard jQuery with object binding$(#view_as_table).click => @.setViewType(Table, true)$(#view_as_thumbs).click => @.setV...
Big Long jQuery Callvar makeSortable = function(){    $(#widgets .col).sortable({        items: div.widget,        dropOnE...
class JKT.GoogleLoader    constructor: (callback) ->        @callback = callback        if google? then @loadComponent() e...
super Is Superclass JKT.Search.TableRenderer    constructor: (results) -> @results = results    render: ->        $(#resul...
class Results    ...    paginate: (start, end) ->        if start? and end?            @results = @results[start..end]    ...
Sources of resistance?
I already know JavaScript          Kudos to you. I do too.      Not a substitute for knowing JS.Your own JS isnt as clean ...
It looks weird. Its the bastard child of Ruby and Python.Once you get used to it, its the JS that looks                 wh...
I dont write JS, I write        jQuery.  No you write JS using jQuery.        I use jQuery too. CS makes your jQuery clean...
Sugar Allergies Are you allergic to "syntactic sugar"?        CS is more than that.We need a better name because we all   ...
Sugar = Noise ReductionBad line noise highly affects the readability of our code. It is true we get used to them,but once ...
Indentation Allergies                  "I like my curly braces"          CS uses Pythonic whitespace         You get used ...
Firebug Will BreakYou lose the correspondence between your     code and line numbers in Firebug           There is no Fire...
What about syntax     highlighting?    No plugin for Eclipse/AptanaUse TextMate, jEdit, gEdit, vim, emacs    The TextMate ...
Maybe on the next projectUnless your current project is almost done     and will never be maintained...Porting that projec...
Where do I start?Dont just dive in or youll be coding before                 youre ready    Read the CS overview a few tim...
Upcoming SlideShare
Loading in …5
×

Real life-coffeescript

2,604 views

Published on

Slides from talk given at Ithaca Web Group and GORGES on CoffeeScript.

The focus is on explaining to people who haven't tried it yet that it's more than syntactic sugar. There are several real life code examples but they were explained verbally so they may not be super helpful if you don't know CoffeeScript yet.

It's an overview, not a tutorial.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,604
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
21
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Real life-coffeescript

  1. 1. Real Life CoffeeScript
  2. 2. What is CoffeeScript? CS is a language that compiles into JavaScript (like HAML and SASS) Not a superset of JS (not like SCSS)Not a JS framework (not a replacement for jQuery)
  3. 3. From the makerCoffeeScript is a little language that compiles into JavaScript. Underneath all of thoseembarrassing braces and semicolons, JavaScript has always had a gorgeous objectmodel at its heart. CoffeeScript is an attempt to expose the good parts of JavaScriptin a simple way. - Josh Ashkenas
  4. 4. Why all the fuss?CS will be a standard part of Rails 3.1 (along with SASS) It makes JS more like Ruby! CS is an npm package, hence a gateway drug to Node.js and Socket.IO
  5. 5. Why use CS? compiles to lint-free JS, nothing fancyeasy to write "good parts javascript" that looks clean makes good practices less tediousHAML and SASS are awesome and now youre using those...
  6. 6. What are the features?Easy variable declaration (lexical scoping) Easy class inheritance and binding Easy instance variables @name => this.name Implicit return from functions "String #{interpolation}"
  7. 7. Semantic Shortcuts -> and => instead of function(){}execute() if that is thing1 and that isnt thing2 and/or/not instead of &&/||/! that = thing1 or thing2 that or= thing3
  8. 8. Conditionals if condition? (no parantheses, ? is .nil? not .blank?) if condition?() to evaluate if a function returns nullthrowAFit() unless @name in ["Paul", "John"]
  9. 9. How much more? list traversal: for result in resultsreturn (transform result for result in results) switch/when/else instead of switch/case/default yes/no, on/off for true/false
  10. 10. Show me some code!
  11. 11. Some ugly JavaScriptvar sortFunction = function(a,b) { if (typeof(a[sort_col]) === number) { // numeric sort if (sort_dir === up) return (a[sort_col] - b[sort_col]); else return (b[sort_col] - a[sort_col]); } else { // string sort var aName = a[sort_col].toLowerCase(), bName = b[sort_col].toLowerCase(); if (sort_dir === up) return (aName > bName); else return (bName > aName); }}this.getResults = function(){ // here is the place to apply filter var results = parent.results; if (filter_text) { results = $.makeArray($.map(results, function(result, i){ var haystack = [result.name, result.brands, result.address, result.city].join(, ) return (haystack.indexOf(filter_text) != -1) ? result : null; })); } if (sort_col && sort_dir) { results = results.sort(sortFunction); } return results;}
  12. 12. class Results setSort: (col, dir) -> if col? and dir? results = _(@results).sortBy (result) -> result[col] @results = if dir is down then results.reverse() else results setFilter: (filter) -> if filter? matching = (needle) -> haystack = _.join needle.name, needle.brand_list, needle.address, needle.city _(haystack).includes(needle) @results = _.select @results, matching
  13. 13. standard jQuery with object binding$(#view_as_table).click => @.setViewType(Table, true)$(#view_as_thumbs).click => @.setViewType(Thumb, true)$(#view_as_list).click => @.setViewType(List, true)
  14. 14. Big Long jQuery Callvar makeSortable = function(){ $(#widgets .col).sortable({ items: div.widget, dropOnEmpty: true, handle: .header h3, appendTo: body, connectWith: .col, ... });makeSortable = -> $(#widgets .col).sortable items: div.widget dropOnEmpty: yes handle: .header h3 appendTo: body connectWith: .col revert: yes cursor: move placeholder: drag-over stop: updateWidgetOrder
  15. 15. class JKT.GoogleLoader constructor: (callback) -> @callback = callback if google? then @loadComponent() else @loadGoogle() loadComponent: -> return loadGoogle: () -> script = document.createElement "script" script.src = "http://www.google.com/jsapi?key=#{JKT.google_api_key}&sensor=false" script.type = "text/javascript" if script.attachEvent? # IE script.attachEvent onreadystatechange, => if script.readyState in [loaded, complete] @loadComponent() else script.onload = => @loadComponent() document.getElementsByTagName("head")[0].appendChild(script)class JKT.MapLoader extends JKT.GoogleLoader loadComponent: -> google.load maps, 3, other_params: "sensor=false" callback: @callback return
  16. 16. super Is Superclass JKT.Search.TableRenderer constructor: (results) -> @results = results render: -> $(#results).html $(#listing_grid).render [{foo:"bar"}] $(#results tbody).html $(#listing_grid_row).render(@results)class JKT.Search.MapRenderer extends JKT.Search.TableRenderer render: -> super if @results.length <= 300 $(#results tbody tr).each -> ...
  17. 17. class Results ... paginate: (start, end) -> if start? and end? @results = @results[start..end] toSentence: -> size = _.size(@results) or 0 if size is 1 then "1 result" else "#{size} results" enoughForMap: -> _.size(@results) < 300 any : -> _.isArray(@results) and _.any(@results)
  18. 18. Sources of resistance?
  19. 19. I already know JavaScript Kudos to you. I do too. Not a substitute for knowing JS.Your own JS isnt as clean as the compiled JSUnless your last name is Resig or Crockford
  20. 20. It looks weird. Its the bastard child of Ruby and Python.Once you get used to it, its the JS that looks whack.
  21. 21. I dont write JS, I write jQuery. No you write JS using jQuery. I use jQuery too. CS makes your jQuery cleaner.
  22. 22. Sugar Allergies Are you allergic to "syntactic sugar"? CS is more than that.We need a better name because we all know sugar is bad for you. Line Noise Reduction
  23. 23. Sugar = Noise ReductionBad line noise highly affects the readability of our code. It is true we get used to them,but once you remove it, theres no way back. - Jose Valim
  24. 24. Indentation Allergies "I like my curly braces" CS uses Pythonic whitespace You get used to it - cost/benefit I really dont understand why using indentation level for blocks is so controversial. You do indentation anyway; you dont want to violate OAOO; it avoids hard-to-spot errors where indentation and begin/end or {/} differ; it looks cleaner; theres no way to have unmatched braces; and I never get indentation wrong, but sometimes I do have to count braces. In other words, dont let thisissue stop you from trying out Python; indentation-denoted blocks are very easy to get used to. -- Falk Bruegmann
  25. 25. Firebug Will BreakYou lose the correspondence between your code and line numbers in Firebug There is no FireCoffeeUse small coffee files to get approximate line correspondenceThe compiled JS is not magical - you can still read it
  26. 26. What about syntax highlighting? No plugin for Eclipse/AptanaUse TextMate, jEdit, gEdit, vim, emacs The TextMate bundle is great!
  27. 27. Maybe on the next projectUnless your current project is almost done and will never be maintained...Porting that project is just what you need to learn CS. Its not "all or nothing": one file at a timeIf you dont like it you can keep the change.
  28. 28. Where do I start?Dont just dive in or youll be coding before youre ready Read the CS overview a few times(http://jashkenas.github.com/coffee-script) Install CS and the TextMate bundle Port a projects JS to CS Write some new CS code

×