SlideShare a Scribd company logo
Rails-like JavaScript
using CoffeeScript,
 Backbone.js and
      Jasmine
     Raimonds Simanovskis
Abstract
Ruby on Rails provides good conventions and structure for your Ruby code so that from the
first day you can start to build your application. But there are practically no conventions and
structure how to develop your JavaScript code and historically Rails was trying to hide any
generated JavaScript from you. Nowadays if you want to build rich UI and efficient web
applications you need to learn and use JavaScript and after some time you understand that
you can't just write a bunch of functions in application.js, you need some conventions and
structure as well.

If you are Ruby developer then you should take a look on CoffeeScript which is programming
language that compiles into JavaScript but with syntax inspired by Ruby and Python. As it is
more similar to Ruby it will be easier to switch between CoffeeScript and Ruby during
development as well as your CoffeeScript code will be smaller and more readable than
JavaScript.

And if you are building rich UI web application in browser then it is worth to try Backbone.js
which provides MVC pattern for browser side UI development which will be more
understandable and easier to maintain than bunch of JavaScript functions that are bound to
bunch of DOM events. And as Backbone.js is made by the same author Jeremy Ashkenas as
CoffeeScript then you can develop your browser side UI in CoffeeScript and Backbone.js.

If you are Ruby developer then testing culture is in your blood and you should feel
uncomfortable if you will not test your JavaScript code. If you prefer RSpec testing framework
in Ruby then in JavaScript (or CoffeeScript) you might like Jasmine testing framework which
syntax is inspired by RSpec.
Example slides
Sample CoffeeScript
# Assignment:                   # Splats:
number   = 42                   race = (winner, runners...) ->
opposite = true                   print winner, runners

# Conditions:                   # Existence:
number = -42 if opposite        alert "I knew it!" if elvis?

# Functions:                    # Array comprehensions:
square = (x) -> x * x           cubes = (math.cube num for num in list)

# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:    Math.sqrt
  square: square
  cube:   (x) -> x * square x
Backbone.js model
     in CoffeeScript
class window.Todo extends Backbone.Model

 # If you don't provide a todo, one will be provided for you.
 EMPTY: "empty todo..."

 # Ensure that each todo created has `content`.
 initialize: ->
   unless this.get "content"
     this.set content: this.EMPTY

 # Toggle the `done` state of this todo item.
 toggle: ->
   this.save done: !this.get "done"
Collection of models
class window.TodoList extends Backbone.Collection

 # Reference to this collection's model.
 model: Todo

  url: '/todos'

 # Filter down the list of all todo items that are finished.
 done: ->
   this.filter (todo) -> todo.get 'done'

 # Filter down the list to only todo items that are still not finished.
 remaining: ->
   this.without this.done()...

 nextOrder: ->
   return 1 unless @length
   this.last().get('order') + 1

 # Todos are sorted by their original insertion order.
 comparator: (todo) ->
   todo.get 'order'
class window.TodoView extends Backbone.View
           tagName: "li"
           template: Handlebars.compile $('#item-template').html()
           events:
             "click .check"              : "toggleDone"
             "dblclick div.todo-content" : "edit"
             "click span.todo-destroy"   : "clear"
             "keypress .todo-input"      : "updateOnEnter"
           initialize: ->
             _.bindAll this, 'render', 'close', 'clear'
             @model.bind 'change', @render
             @model.bind 'clear', @clear
           render: ->



Sample
             $(@el).html @template @model.toJSON()
             this.setContent()
             this
           setContent: ->
             content = @model.get 'content'


 view
             this.$('.todo-content').text content
             @input = this.$('.todo-input')
             @input.bind 'blur', @close
             @input.val content
           toggleDone: ->
             @model.toggle()
           edit: ->
             $(@el).addClass "editing"
             @input.focus()
           close: ->
             @model.save content: @input.val()
             $(@el).removeClass "editing"
           updateOnEnter: (e) ->
             this.close() if e.keyCode == 13
           clear: ->
             $(@el).remove()
             @model.destroy()
Sample Jasmine
            tests
describe "Todo", ->
  todo = null
  ajaxCall = (param) -> jQuery.ajax.mostRecentCall.args[0][param]

  beforeEach ->
    todo = new Todo
    todos = new TodoList [todo]

  it "should initialize with empty content", ->
    expect(todo.get "content").toEqual "empty todo..."

  it "should initialize as not done", ->
    expect(todo.get "done").toBeFalsy()

  it "should save after toggle", ->
    spyOn jQuery, "ajax"
    todo.toggle()
    expect(ajaxCall "url").toEqual "/todos"
    expect(todo.get "done").toBeTruthy()

More Related Content

What's hot (20)

PDF
Coffeescript: No really, it's just Javascript
Brian Mann
 
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
PDF
RSpec. Part 2
Vladimir Dementyev
 
PDF
RSpec. Part 1
Vladimir Dementyev
 
PDF
CoffeeScript
Eddie Kao
 
PDF
Ruby Metaprogramming
Nando Vieira
 
PPTX
Rails, Postgres, Angular, and Bootstrap: The Power Stack
David Copeland
 
PDF
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
Zigotto Tecnologia
 
PDF
Plugin jQuery, Design Patterns
Robert Casanova
 
PPT
JavaScript on Rails 튜토리얼
Sukjoon Kim
 
PDF
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
PDF
Mojolicious, real-time web framework
taggg
 
PDF
Thymeleaf Introduction
Anthony Chen
 
PDF
Mojolicious: what works and what doesn't
Cosimo Streppone
 
KEY
Mojolicious - A new hope
Marcus Ramberg
 
ODP
Mojolicious on Steroids
Tudor Constantin
 
PDF
SINATRA + HAML + TWITTER
Elber Ribeiro
 
KEY
jQuery Plugin Creation
benalman
 
PPTX
jQuery PPT
Dominic Arrojado
 
Coffeescript: No really, it's just Javascript
Brian Mann
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
RSpec. Part 2
Vladimir Dementyev
 
RSpec. Part 1
Vladimir Dementyev
 
CoffeeScript
Eddie Kao
 
Ruby Metaprogramming
Nando Vieira
 
Rails, Postgres, Angular, and Bootstrap: The Power Stack
David Copeland
 
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
Zigotto Tecnologia
 
Plugin jQuery, Design Patterns
Robert Casanova
 
JavaScript on Rails 튜토리얼
Sukjoon Kim
 
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Mojolicious, real-time web framework
taggg
 
Thymeleaf Introduction
Anthony Chen
 
Mojolicious: what works and what doesn't
Cosimo Streppone
 
Mojolicious - A new hope
Marcus Ramberg
 
Mojolicious on Steroids
Tudor Constantin
 
SINATRA + HAML + TWITTER
Elber Ribeiro
 
jQuery Plugin Creation
benalman
 
jQuery PPT
Dominic Arrojado
 

Similar to Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine (20)

KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
PDF
Viking academy backbone.js
Bert Wijnants
 
PDF
Writing Maintainable JavaScript
Andrew Dupont
 
KEY
Single Page Web Apps with Backbone.js and Rails
Prateek Dayal
 
KEY
Prateek dayal backbonerails-110528024926-phpapp02
Revath S Kumar
 
PDF
Introduction to Backbone.js for Rails developers
AoteaStudios
 
PDF
Backbone.js
Ivano Malavolta
 
PPTX
Backbonejs for beginners
Divakar Gu
 
PPTX
Taming that client side mess with Backbone.js
Jarod Ferguson
 
ODP
Javascript frameworks: Backbone.js
Soós Gábor
 
PDF
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh
 
KEY
Backbonification for dummies - Arrrrug 10/1/2012
Dimitri de Putte
 
PPTX
Planbox Backbone MVC
Acquisio
 
PDF
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
PDF
Backbone.js: Run your Application Inside The Browser
Howard Lewis Ship
 
PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
PDF
Building a JavaScript Library
jeresig
 
PDF
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
PPTX
Introduction to Knockoutjs
jhoguet
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Viking academy backbone.js
Bert Wijnants
 
Writing Maintainable JavaScript
Andrew Dupont
 
Single Page Web Apps with Backbone.js and Rails
Prateek Dayal
 
Prateek dayal backbonerails-110528024926-phpapp02
Revath S Kumar
 
Introduction to Backbone.js for Rails developers
AoteaStudios
 
Backbone.js
Ivano Malavolta
 
Backbonejs for beginners
Divakar Gu
 
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Javascript frameworks: Backbone.js
Soós Gábor
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh
 
Backbonification for dummies - Arrrrug 10/1/2012
Dimitri de Putte
 
Planbox Backbone MVC
Acquisio
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Backbone.js: Run your Application Inside The Browser
Howard Lewis Ship
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
Building a JavaScript Library
jeresig
 
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Introduction to Knockoutjs
jhoguet
 
Ad

More from Raimonds Simanovskis (20)

PDF
Profiling Mondrian MDX Requests in a Production Environment
Raimonds Simanovskis
 
PDF
Improve Mondrian MDX usability with user defined functions
Raimonds Simanovskis
 
PDF
Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015
Raimonds Simanovskis
 
PDF
Data Warehouses and Multi-Dimensional Data Analysis
Raimonds Simanovskis
 
PDF
mondrian-olap JRuby library
Raimonds Simanovskis
 
PDF
eazyBI Overview - Embedding Mondrian in other applications
Raimonds Simanovskis
 
PDF
Atvērto datu izmantošanas pieredze Latvijā
Raimonds Simanovskis
 
PDF
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
PDF
JRuby - Programmer's Best Friend on JVM
Raimonds Simanovskis
 
PDF
Agile Operations or How to sleep better at night
Raimonds Simanovskis
 
PDF
TDD - Why and How?
Raimonds Simanovskis
 
PDF
Analyze and Visualize Git Log for Fun and Profit
Raimonds Simanovskis
 
PDF
PL/SQL Unit Testing Can Be Fun
Raimonds Simanovskis
 
PDF
opendata.lv Case Study - Promote Open Data with Analytics and Visualizations
Raimonds Simanovskis
 
PDF
Extending Oracle E-Business Suite with Ruby on Rails
Raimonds Simanovskis
 
PDF
RailsWayCon: Multidimensional Data Analysis with JRuby
Raimonds Simanovskis
 
PDF
Why Every Tester Should Learn Ruby
Raimonds Simanovskis
 
PDF
Multidimensional Data Analysis with JRuby
Raimonds Simanovskis
 
PDF
Rails on Oracle 2011
Raimonds Simanovskis
 
PDF
How to Adopt Agile at Your Organization
Raimonds Simanovskis
 
Profiling Mondrian MDX Requests in a Production Environment
Raimonds Simanovskis
 
Improve Mondrian MDX usability with user defined functions
Raimonds Simanovskis
 
Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015
Raimonds Simanovskis
 
Data Warehouses and Multi-Dimensional Data Analysis
Raimonds Simanovskis
 
mondrian-olap JRuby library
Raimonds Simanovskis
 
eazyBI Overview - Embedding Mondrian in other applications
Raimonds Simanovskis
 
Atvērto datu izmantošanas pieredze Latvijā
Raimonds Simanovskis
 
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
JRuby - Programmer's Best Friend on JVM
Raimonds Simanovskis
 
Agile Operations or How to sleep better at night
Raimonds Simanovskis
 
TDD - Why and How?
Raimonds Simanovskis
 
Analyze and Visualize Git Log for Fun and Profit
Raimonds Simanovskis
 
PL/SQL Unit Testing Can Be Fun
Raimonds Simanovskis
 
opendata.lv Case Study - Promote Open Data with Analytics and Visualizations
Raimonds Simanovskis
 
Extending Oracle E-Business Suite with Ruby on Rails
Raimonds Simanovskis
 
RailsWayCon: Multidimensional Data Analysis with JRuby
Raimonds Simanovskis
 
Why Every Tester Should Learn Ruby
Raimonds Simanovskis
 
Multidimensional Data Analysis with JRuby
Raimonds Simanovskis
 
Rails on Oracle 2011
Raimonds Simanovskis
 
How to Adopt Agile at Your Organization
Raimonds Simanovskis
 
Ad

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
July Patch Tuesday
Ivanti
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
July Patch Tuesday
Ivanti
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 

Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine

  • 1. Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine Raimonds Simanovskis
  • 2. Abstract Ruby on Rails provides good conventions and structure for your Ruby code so that from the first day you can start to build your application. But there are practically no conventions and structure how to develop your JavaScript code and historically Rails was trying to hide any generated JavaScript from you. Nowadays if you want to build rich UI and efficient web applications you need to learn and use JavaScript and after some time you understand that you can't just write a bunch of functions in application.js, you need some conventions and structure as well. If you are Ruby developer then you should take a look on CoffeeScript which is programming language that compiles into JavaScript but with syntax inspired by Ruby and Python. As it is more similar to Ruby it will be easier to switch between CoffeeScript and Ruby during development as well as your CoffeeScript code will be smaller and more readable than JavaScript. And if you are building rich UI web application in browser then it is worth to try Backbone.js which provides MVC pattern for browser side UI development which will be more understandable and easier to maintain than bunch of JavaScript functions that are bound to bunch of DOM events. And as Backbone.js is made by the same author Jeremy Ashkenas as CoffeeScript then you can develop your browser side UI in CoffeeScript and Backbone.js. If you are Ruby developer then testing culture is in your blood and you should feel uncomfortable if you will not test your JavaScript code. If you prefer RSpec testing framework in Ruby then in JavaScript (or CoffeeScript) you might like Jasmine testing framework which syntax is inspired by RSpec.
  • 4. Sample CoffeeScript # Assignment: # Splats: number = 42 race = (winner, runners...) -> opposite = true print winner, runners # Conditions: # Existence: number = -42 if opposite alert "I knew it!" if elvis? # Functions: # Array comprehensions: square = (x) -> x * x cubes = (math.cube num for num in list) # Arrays: list = [1, 2, 3, 4, 5] # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x
  • 5. Backbone.js model in CoffeeScript class window.Todo extends Backbone.Model # If you don't provide a todo, one will be provided for you. EMPTY: "empty todo..." # Ensure that each todo created has `content`. initialize: -> unless this.get "content" this.set content: this.EMPTY # Toggle the `done` state of this todo item. toggle: -> this.save done: !this.get "done"
  • 6. Collection of models class window.TodoList extends Backbone.Collection # Reference to this collection's model. model: Todo url: '/todos' # Filter down the list of all todo items that are finished. done: -> this.filter (todo) -> todo.get 'done' # Filter down the list to only todo items that are still not finished. remaining: -> this.without this.done()... nextOrder: -> return 1 unless @length this.last().get('order') + 1 # Todos are sorted by their original insertion order. comparator: (todo) -> todo.get 'order'
  • 7. class window.TodoView extends Backbone.View tagName: "li" template: Handlebars.compile $('#item-template').html() events: "click .check" : "toggleDone" "dblclick div.todo-content" : "edit" "click span.todo-destroy" : "clear" "keypress .todo-input" : "updateOnEnter" initialize: -> _.bindAll this, 'render', 'close', 'clear' @model.bind 'change', @render @model.bind 'clear', @clear render: -> Sample $(@el).html @template @model.toJSON() this.setContent() this setContent: -> content = @model.get 'content' view this.$('.todo-content').text content @input = this.$('.todo-input') @input.bind 'blur', @close @input.val content toggleDone: -> @model.toggle() edit: -> $(@el).addClass "editing" @input.focus() close: -> @model.save content: @input.val() $(@el).removeClass "editing" updateOnEnter: (e) -> this.close() if e.keyCode == 13 clear: -> $(@el).remove() @model.destroy()
  • 8. Sample Jasmine tests describe "Todo", -> todo = null ajaxCall = (param) -> jQuery.ajax.mostRecentCall.args[0][param] beforeEach -> todo = new Todo todos = new TodoList [todo] it "should initialize with empty content", -> expect(todo.get "content").toEqual "empty todo..." it "should initialize as not done", -> expect(todo.get "done").toBeFalsy() it "should save after toggle", -> spyOn jQuery, "ajax" todo.toggle() expect(ajaxCall "url").toEqual "/todos" expect(todo.get "done").toBeTruthy()