SlideShare a Scribd company logo
Introduction to




for Rails developers
      Alex Korban
What is it?
•   Small JavaScript library to organise your UI and
    data on the client
•   Follows the MVC pattern
•   Doesn't provide widgets or HTML structure
Why use it?
•   Libraries like jQuery don't help with code
    structure
•   Doesn't assume anything about your UI
•   Flexible with regards to data persistence
•   You can use an HTML templating engine of your
    choice
•   Only hard dependency is Underscore.js
•   Only 3.9kB minified
What's in it?
•   Controller
•   View
•   Model
•   Collection
•   Hash change and history handling
Controller
     class AppController extends Backbone.Controller
       routes:                 handler method
            "users": "users"

URL hash "users/:cid/edit": "edit"
fragment             parameter part
       users: ->
            @view = new UserListView


       edit: (cid) ->
            @view = new EditUserView { model: Users.getByCid(cid) }


     $ ->
       window.app = new AppController()
       Backbone.history.start()
View
  class UsersView extends Backbone.View
    tagName: "div"     the view's DOM element parameters
    id: "users"

    events:                                   DOM event handler
      "click .add_user": "click_add_user"
event
type                     selector
    constructor(@users): ->
      @template = _.template("HTML string with params to interpolate")
      @users.bind "add", @add_user
                                              Bind collection event to view method
      @users.bind "refresh", @render

    render: ->
      $(@el).html @template(@users)

    click_add_user: ->
      @users.add()         Triggers a call to add_user

    add_user: (user) =>
      view = new UserView {model: user}
      @el.append view.render()
Templates
•   Since Underscore.js is included, you can use
    _.template which provides variable interpolation
    and arbitrary JavaScript execution
•   You can use a different templating engine such
    as Mustache.js, Haml-js or Eco
•   You could even insert elements into the DOM
    instead of using templates
Managing templates
•   One option is to use Jammit (documentcloud.github.com/jammit)
•   JavaScript templates are stored alongside Rails views:
    // app/views/users/user.jst
    <div class = "user">
      <h2>Name: <%= name %></h2>
      <em>Hometown: <%= birthplace %></em>
    </div>

•   Jammit allows different templating engines
•   Jammit concatenates, compresses and precompiles templates
•   Then you can access a template on the client side like this:

    JST[“users/user”]({name: “Joe”, birthplace: “Picton”})
Models and collections
class User extends Backbone.Model
 is_invited: ->
   @get("invitation_token") != null
          get() and set() provide access to the attribute hash
class UserCollection extends Backbone.Collection
 model: User
 url: "/users"


users = new UserCollection()
users.fetch()                                 # loads models from the server
users.add [{name: "John"}, {name: "Mary"}]             Adds 2 User instances to the
                                                       collection because model is
is_invited = users.at(0).is_invited()
                                                       defined in UserCollection
Persistence
•   Backbone.sync() is called every time Backbone reads or saves a model
    to the server
•   The default is RESTful JSON requests using $.ajax():
         create → POST          /collection
         read      → GET        /collection[/id]
         update → PUT           /collection/id
         delete → DELETE        /collection/id
•   Responding to a “read” request: send down an array of model attribute
    objects
•   Responding to a “create” or “update”: send the attributes of the model
    changed by the server
•   You can override sync() to use XML or LocalStorage
Persistence & Rails
•   With JSON persistence, your Rails update method might be:

      def update
        user = User.find params[:id]
        user.update_attributes params
        render json: user
      end
•   Set Backbone.emulateHTTP = true to replace PUT and
    DELETE requests with a POST + _method parameter
•   Set config.active_record.include_root_in_json = false
    or override parse() in Backbone models (see
    gist.github.com/957474 for an example)
Initialising data
•   One option is to include the data when rendering the Rails view:
    / index.haml
    :javascript                                    Supplied by a Rails controller
      this.users.refresh(#{@users.to_json(only: User::JSON_FIELDS)});
      this.checklists.refresh(#{@checklists.to_json});
                                          This just sets collection data from the argument
    #content
•   The other option is to get the data on page load:
    :javascript
      $(function() {
         this.users.fetch();                     This performs an AJAX request
         this.checklists.fetch();
      });
•   Your UI will need to handle the delay in loading the data
•   You probably want to preload just enough data to display the initial page, and load the rest
    using .fetch() as needed
Alternatives
•   Sproutcore (sproutcore.com)
•   Cappuccino (cappuccino.org)
•   KnockoutJS (knockoutjs.com)
•   JavaScriptMVC (javascriptmvc.com)
•   Sammy.js (sammyjs.org)
Questions?




Documentation: documentcloud.github.com/backbone
      These slides: devblog.aoteastudios.com

More Related Content

What's hot

Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
DicodingEvent
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptAndrew Lovett-Barron
 
Backbone js in action
Backbone js in actionBackbone js in action
Backbone js in action
Usha Guduri
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascriptDsixE Inc
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
Makarand Bhatambarekar
 
BackboneJS and friends
BackboneJS and friendsBackboneJS and friends
BackboneJS and friendsScott Cowan
 
Go Fullstack: JSF for Public Sites (CONFESS 2012)
Go Fullstack: JSF for Public Sites (CONFESS 2012)Go Fullstack: JSF for Public Sites (CONFESS 2012)
Go Fullstack: JSF for Public Sites (CONFESS 2012)
Michael Kurz
 
Go Fullstack: JSF for Public Sites (CONFESS 2013)
Go Fullstack: JSF for Public Sites (CONFESS 2013)Go Fullstack: JSF for Public Sites (CONFESS 2013)
Go Fullstack: JSF for Public Sites (CONFESS 2013)
Michael Kurz
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
maltiyadav
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
soelinn
 

What's hot (18)

Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate Javascript
 
Backbone js in action
Backbone js in actionBackbone js in action
Backbone js in action
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuery
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascript
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
BackboneJS and friends
BackboneJS and friendsBackboneJS and friends
BackboneJS and friends
 
Go Fullstack: JSF for Public Sites (CONFESS 2012)
Go Fullstack: JSF for Public Sites (CONFESS 2012)Go Fullstack: JSF for Public Sites (CONFESS 2012)
Go Fullstack: JSF for Public Sites (CONFESS 2012)
 
Go Fullstack: JSF for Public Sites (CONFESS 2013)
Go Fullstack: JSF for Public Sites (CONFESS 2013)Go Fullstack: JSF for Public Sites (CONFESS 2013)
Go Fullstack: JSF for Public Sites (CONFESS 2013)
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 

Similar to Introduction to Backbone.js for Rails developers

Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
Akshay Mathur
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Ovadiah Myrgorod
 
Modern android development
Modern android developmentModern android development
Modern android development
Khiem-Kim Ho Xuan
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30fiyuer
 
Backbone js
Backbone jsBackbone js
Backbone js
husnara mohammad
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
Ivano Malavolta
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Ivano Malavolta
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
Hossein Zahed
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
Ivano Malavolta
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
Chandra Sekar
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Ivano Malavolta
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Arun Gupta
 
The Grid the Brad and the Ugly: Using Grids to Improve Your Applications
The Grid the Brad and the Ugly: Using Grids to Improve Your ApplicationsThe Grid the Brad and the Ugly: Using Grids to Improve Your Applications
The Grid the Brad and the Ugly: Using Grids to Improve Your Applications
balassaitis
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
Andrea Prearo
 

Similar to Introduction to Backbone.js for Rails developers (20)

Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
Modern android development
Modern android developmentModern android development
Modern android development
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
 
The Grid the Brad and the Ugly: Using Grids to Improve Your Applications
The Grid the Brad and the Ugly: Using Grids to Improve Your ApplicationsThe Grid the Brad and the Ugly: Using Grids to Improve Your Applications
The Grid the Brad and the Ugly: Using Grids to Improve Your Applications
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 

Introduction to Backbone.js for Rails developers

  • 1. Introduction to for Rails developers Alex Korban
  • 2. What is it? • Small JavaScript library to organise your UI and data on the client • Follows the MVC pattern • Doesn't provide widgets or HTML structure
  • 3. Why use it? • Libraries like jQuery don't help with code structure • Doesn't assume anything about your UI • Flexible with regards to data persistence • You can use an HTML templating engine of your choice • Only hard dependency is Underscore.js • Only 3.9kB minified
  • 4. What's in it? • Controller • View • Model • Collection • Hash change and history handling
  • 5. Controller class AppController extends Backbone.Controller routes: handler method "users": "users" URL hash "users/:cid/edit": "edit" fragment parameter part users: -> @view = new UserListView edit: (cid) -> @view = new EditUserView { model: Users.getByCid(cid) } $ -> window.app = new AppController() Backbone.history.start()
  • 6. View class UsersView extends Backbone.View tagName: "div" the view's DOM element parameters id: "users" events: DOM event handler "click .add_user": "click_add_user" event type selector constructor(@users): -> @template = _.template("HTML string with params to interpolate") @users.bind "add", @add_user Bind collection event to view method @users.bind "refresh", @render render: -> $(@el).html @template(@users) click_add_user: -> @users.add() Triggers a call to add_user add_user: (user) => view = new UserView {model: user} @el.append view.render()
  • 7. Templates • Since Underscore.js is included, you can use _.template which provides variable interpolation and arbitrary JavaScript execution • You can use a different templating engine such as Mustache.js, Haml-js or Eco • You could even insert elements into the DOM instead of using templates
  • 8. Managing templates • One option is to use Jammit (documentcloud.github.com/jammit) • JavaScript templates are stored alongside Rails views: // app/views/users/user.jst <div class = "user"> <h2>Name: <%= name %></h2> <em>Hometown: <%= birthplace %></em> </div> • Jammit allows different templating engines • Jammit concatenates, compresses and precompiles templates • Then you can access a template on the client side like this: JST[“users/user”]({name: “Joe”, birthplace: “Picton”})
  • 9. Models and collections class User extends Backbone.Model is_invited: -> @get("invitation_token") != null get() and set() provide access to the attribute hash class UserCollection extends Backbone.Collection model: User url: "/users" users = new UserCollection() users.fetch() # loads models from the server users.add [{name: "John"}, {name: "Mary"}] Adds 2 User instances to the collection because model is is_invited = users.at(0).is_invited() defined in UserCollection
  • 10. Persistence • Backbone.sync() is called every time Backbone reads or saves a model to the server • The default is RESTful JSON requests using $.ajax(): create → POST /collection read → GET /collection[/id] update → PUT /collection/id delete → DELETE /collection/id • Responding to a “read” request: send down an array of model attribute objects • Responding to a “create” or “update”: send the attributes of the model changed by the server • You can override sync() to use XML or LocalStorage
  • 11. Persistence & Rails • With JSON persistence, your Rails update method might be: def update user = User.find params[:id] user.update_attributes params render json: user end • Set Backbone.emulateHTTP = true to replace PUT and DELETE requests with a POST + _method parameter • Set config.active_record.include_root_in_json = false or override parse() in Backbone models (see gist.github.com/957474 for an example)
  • 12. Initialising data • One option is to include the data when rendering the Rails view: / index.haml :javascript Supplied by a Rails controller this.users.refresh(#{@users.to_json(only: User::JSON_FIELDS)}); this.checklists.refresh(#{@checklists.to_json}); This just sets collection data from the argument #content • The other option is to get the data on page load: :javascript $(function() { this.users.fetch(); This performs an AJAX request this.checklists.fetch(); }); • Your UI will need to handle the delay in loading the data • You probably want to preload just enough data to display the initial page, and load the rest using .fetch() as needed
  • 13. Alternatives • Sproutcore (sproutcore.com) • Cappuccino (cappuccino.org) • KnockoutJS (knockoutjs.com) • JavaScriptMVC (javascriptmvc.com) • Sammy.js (sammyjs.org)
  • 14. Questions? Documentation: documentcloud.github.com/backbone These slides: devblog.aoteastudios.com