Tuesday, September 13, 2011

Advantages of CoffeeScript When Working with jQuery Templates

Working with jQuery Templates in CoffeeScript is very similar to working with them in JavaScript. However, there are a couple of CoffeeScript features that can make it even easier.

Here's a simple example (based on an example in the jQuery Template documentation):

$(document).ready ->
do ($ = jQuery) ->
selectedItem = null
summaryMarkup = "<div class='movieSummary'><div>Name: ${Name}</div></div>"
detailMarkup = "<div class='movieDetail'><div>Name: ${Name}</div><div>Director: ${Director}</div></div>"
$.template 'summaryTemplate', summaryMarkup
$.template 'detailTemplate', detailMarkup
movies = [ {Name: 'The Red Violin', Director: 'François Girard'}
{Name: 'Eyes Wide Shut', Director: 'Stanley Kubrick'}
{Name: 'The Inheritance', Director: 'Mauro Bolognini'} ]
$.tmpl('summaryTemplate', movies).appendTo '#movieList'
$( '#movieList' ).delegate '.movieSummary', 'click', () ->
if selectedItem
selectedItem.tmpl = $.template 'summaryTemplate'
selectedItem.update()
selectedItem = $.tmplItem this
selectedItem.tmpl = $.template 'detailTemplate'
selectedItem.update()
.delegate '.movieDetail', 'click', () ->
selectedItem.tmpl = $.template 'summaryTemplate'
selectedItem.update()
selectedItem = null

As you can see, it's pretty similar to its JavaScript counterpart.

How can CoffeeScript make this better?

Enter Heredoc and String Interpolation...

Heredoc: Heredocs allow you to specify multi-line, formatted text. This can be useful when defining the template markup.

With heredocs, the markup from the previous example changes to this:

summaryMarkup = """
<div class='movieSummary'><
div>Name: ${Name}</div>
</div>
"""
detailMarkup = """
<div class='movieDetail'>
<div>Name: ${Name}</div>
<div>Director: ${Director}</div>
</div>
"""

String Interpolation: CoffeeScript also provides Ruby style string interpolation. Here's an example of the markup after taking advantage of the string interpolation feature (Note: String interpolation only occurs within double-quoted strings and double-quoted heredocs):

commonMarkup = "<div>Name: ${Name}</div>"
summaryMarkup = """<div class='movieSummary'>#{commonMarkup}</div>"""
detailMarkup = """
<div class='movieDetail'>
#{commonMarkup}
<div>Director: ${Director}</div>
</div>
"""

Want to see it in action?

Go to http://tinkerbin.com/w0QoscT9, change the JavaScript Format drop down to CoffeeScript, then click the Run button.

No comments:

Post a Comment