SlideShare a Scribd company logo
1 of 14
Download to read offline
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 actionUsha Guduri
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascriptDsixE Inc
 
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 Playframeworkmaltiyadav
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4soelinn
 

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 JSAkshay 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
 
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 for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile appsIvano 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'sAntônio Roberto Silva
 
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 - VS2015Hossein Zahed
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember Chandra Sekar
 
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 GAERon 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.0Arun 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 Applicationsbalassaitis
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView ScrollingAndrea 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

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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