SlideShare a Scribd company logo
1 of 89
SINGLE PAGE APPS
      WITH
BACKBONE.JS & RAILS
      Prateek Dayal
     SupportBee.com
HOW I LEARNED TO STOP
      WORRYING
 AND LOVE JAVSCRIPT!
BUT I LOVE JQUERY!
VANILLA JQUERY IS GREAT
 FOR A SIMPLE WEBSITE
BUT YOU WANT TO BUILD A
SINGLE PAGE APPLICATION
Unless you’re a really fastidious coder, some sort of
library to help structure large-scale JavaScript
applications is important -- it’s far too easy to
degenerate into nested piles of jQuery callbacks, all
tied to concrete DOM elements.

                                      Jeremy Ashkenas
;)
COMPLEX SINGLE PAGE APPS
         HAVE
• All   of the client logic in Javascript
• All   of the client logic in Javascript

• Updates     to many parts of the UI on changes to
 data
• All   of the client logic in Javascript

• Updates     to many parts of the UI on changes to
 data

• Templating     on the client side
TO NOT GO CRAZY
BUILDING IT, YOU NEED
•A   MVC like pattern to keep the code clean
•A   MVC like pattern to keep the code clean

•Atemplating language like HAML/ERB to easily
render view elements
•A   MVC like pattern to keep the code clean

•Atemplating language like HAML/ERB to easily
render view elements

•A   better way to manage events and callbacks
•A   MVC like pattern to keep the code clean

•Atemplating language like HAML/ERB to easily
render view elements

•A   better way to manage events and callbacks

•A   way to preserver browser’s back button
•A   MVC like pattern to keep the code clean

•A templating language like HAML/ERB to easily
 render view elements

•A   better way to manage events and callbacks

•A   way to preserver browser’s back button

• Easy Testing   :)
FORTUNATELY, THERE IS HELP!
SproutCore
Cappuccino
BUT THEY ARE BIG
AND HAVE A
LEARNING CURVE
• 3.9   kb packed and gzipped
• 3.9   kb packed and gzipped

• Only   dependency is underscore.js
• 3.9   kb packed and gzipped

• Only   dependency is underscore.js

• You    need jQuery or Zepto for Ajax
• 3.9   kb packed and gzipped

• Only   dependency is underscore.js

• You    need jQuery or Zepto for Ajax

• Annotated    source code
MVC
MODELS, VIEWS &
 COLLECTIONS
MODELS
MODELS


• Data   is represented as Models
MODELS


• Data   is represented as Models

• Can   be Created, Validated, Destroyed & Persisted on Server
MODELS


• Data   is represented as Models

• Can   be Created, Validated, Destroyed & Persisted on Server

• Attribute   changes trigger a ‘change’ event
SB.Models.TicketSummary = Backbone.Model.extend({
  id: null,
  subject: null,
  name: 'ticket',
});
COLLECTIONS
COLLECTIONS

•A   collection of models
COLLECTIONS

•A   collection of models

• Triggers   events like add/remove/refresh
COLLECTIONS

•A   collection of models

• Triggers   events like add/remove/refresh

• Can   fetch models from a given url
COLLECTIONS

•A   collection of models

• Triggers   events like add/remove/refresh

• Can   fetch models from a given url

• Can keep the models sorted if you define a comparator
 function
SB.Collections.TicketList = Backbone.Collection.extend({
  model: SB.Models.TicketSummary,

  url: "/tickets",
  name: "tickets",

   initialize: function(models, options){
     // Init stuff if you want
   }
});
VIEWS
VIEWS



• They   are more like Rails’ Controllers
VIEWS



• They   are more like Rails’ Controllers

• Responsiblefor instantiating Collections and binding events
 that update the UI
SB.Views.TicketListView = Backbone.View.extend({

  tagName: 'ul',

  initialize: function(){

    this.ticketList = new SB.Collections.TicketList;

    _.bindAll(this, 'addOne', 'addAll');


    this.ticketList.bind('add', this.addOne);

    this.ticketList.bind('refresh', this.addAll);

    this.ticketList.bind('all', this.render);


    this.ticketList.fetch();

  },

  addAll: function(){

    this.ticketList.each(this.addOne);
  },

   addOne: function(ticket){

    var view = new SB.Views.TicketSummaryView({model:ticket});

    $(this.el).append(view.render().el);
   }
});
SB.Views.TicketSummary = Backbone.View.extend({

 
     
 
 
 
 
 
 
 
 
  initialize: function(){

 _.bind(this, 'render');

 if(this.model !== undefined){

      this.model.view = this;

 }
  },

 events: {

 'click': 'openTicket'
 },

 openTicket: function(){

 window.location = "#ticket/" + this.model.id;
 },

  render: function(){

 $(this.el).html(SB.Views.Templates['tickets/summary']
(this.model.toJSON()));

 return this;
  }

 
    
 
 
 
 
 
 
 
 
});
HANDLEBARS!
{{#ticket}}
  <div class="listing-cell name">
   <p>{{nameOrEmail requester}} ({{replies_count}})</p>
  </div>

  <div class="listing-cell subject">
    
 <a href="#{{id}}">
    
 {{#unread}}
    
 <b>{{subject}}</b>
    
 {{/unread}}
    
 {{^unread}}
    
 {{subject}}
    
 {{/unread}}
    
 </a>
  </div>
{{/ticket}}
URLS
URLS



• Collections   can have a url
URLS



• Collections   can have a url

• Models   can have a url or they can derive it from collection’s
 url
◦   create → POST   /collection
◦   read → GET   /collection[/id]
◦   update → PUT   /collection/id
◦   delete → DELETE   /collection/id
FINALLY, CONTROLLERS
• Used   for setting up the routes
• Used   for setting up the routes

• You   can add new routes during runtime
SB.Controllers.AgentHome = Backbone.Controller.extend({
 routes: {

 "": "dashboard", // http://app_url

 ":id": "openTicket" // http://app_url#id
 },

    dashboard: function(){

      var view = new SB.Views.TicketListView;

      $("#ticket").hide();

      $("#list").html(view.el);

      $("#list").show();
    },

  openTicket: function(id){

 var view = new SB.Views.TicketView({model : new
SB.Models.Ticket({id : id})});

 $("#list").hide();

 $("#ticket").html(view.el);

 $("#ticket").show();
  }
});
window.controller = new SB.Controllers.AgentHome
• Initiates   a new controller instance
• Initiates   a new controller instance

• which   matches the dashboard route
• Initiates   a new controller instance

• which   matches the dashboard route

• and   creates a instance of TicketListView
• Initiates   a new controller instance

• which   matches the dashboard route

• and   creates a instance of TicketListView

• and   a TicketList collection is created
• TicketList
           collection fetches tickets and triggers the
 refresh event
• TicketList
           collection fetches tickets and triggers the
 refresh event

• Refresh handler renders a TicketSummary view for
 each ticket and adds it to the top level element
• Every Ticket   Summary row has an onclick handler
• Every Ticket   Summary row has an onclick handler

• which   changes to url to #ticket_id
• Every Ticket   Summary row has an onclick handler

• which   changes to url to #ticket_id

• which   matches the openTicket route
SERVER SIDE
ActiveRecord::Base.include_root_in_json = false
• Youcan use as_json to customize the json
 responses
• Youcan use as_json to customize the json
 responses

• Or   you can use Restfulie
• Youcan use as_json to customize the json
 responses

• Or   you can use Restfulie

• Restfulie   lets you easily put links in representations
 too
collection(@items, :root => "items") do |items|
    items.link "self", items_url

      items.members do |m, item|
          m.link :self, item_url(item)
          m.values { |values|
              values.name   item.name
          }
      end
end
NOT JUST FOR API BACKED
        MODELS
//window.AgentHomeController = new SB.Controllers.AgentHome;
window.mainView = new SB.Views.Main;
mainView.screens.add(new SB.Models.Screen({
  title: 'Dashboard',
  href: '#dashboard',
  listings: [

 {

 
       title: 'New Tickets',

 
       url: '/tickets?label=unanswered&replies=false'

 },

 {

 
       title: 'Ongoing Tickets',

 
       url: '/tickets?label=unanswered&replies=true'

 },

 {

 
       title: 'Starred Tickets',

 
       url: '/tickets?starred=true'

 }
   ]
}));
TESTING
JASMINE FTW!
beforeEach(function(){
   var ticket = new SB.Models.TicketSummary({id: 1,

 
     
 
 
 
 
 
 
 
 
 subject: "A Ticket",

 
     
 
 
 
 
 
 
 
 
 replies_count: 0,

 
     
 
 
 
 
 
 
 
 
 requester: {id : 1,

 
     
 
 
 
 
 
 
 
 
 email: 'requester@example.com',

 
     
 
 
 
 
 
 
 
 
 name: 'Requester',

 
     
 
 
 
 
 
 
 
 
 thumbnail: 'thumbnail-url'}

 
     
 
 
 
 
 
 
 
 
 });
   this.view = new SB.Views.TicketSummary({model: ticket});
   this.view.render();
});

it("should render a ticket summary correctly", function(){
   expect($(this.view.el)).toHaveText(/A Ticket/);
   expect($(this.view.el)).toHaveText(/Requester/);
});

it("should change the url on click", function(){
   var currentLoc = window.location.toString();
   $(this.view.el).click();
   expect(window.location.toString()).toBe(currentLoc + "ticket#1");
});
SINON FOR MOCKS/STUBS
beforeEach(function(){
  this.server = sinon.fakeServer.create();
  this.server.respondWith("GET", "/tickets_url_mock_server",

 
     
 
 
 
       [200, { "Content-Type": "application/json" },

 
     
 
 
 
 
 '{"tickets":[{"id": 1, "subject": "Ticket 1"},{"id": 2, "subject":
"Ticket 2"}]}'

 
     
 
 
 
 ]);
});

it("should instantiate view when tickets are fetched", function(){

  var viewMock = sinon.mock(SB.Views);

  viewMock.expects("TicketSummary").once().returns(new Backbone.View);
  viewMock.expects("TicketSummary").once().returns(new Backbone.View);

  var view = new SB.Views.TicketList({url: "/tickets_url_mock_server"});

   this.server.respond();
   viewMock.verify();
   expect($(view.render().el).children().length).toBe(2);
});
QUESTIONS?

prateek@supportbee.com
     @prateekdayal

  http://supportbee.com

More Related Content

What's hot

Templates
TemplatesTemplates
Templatessoon
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesjerryorr
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Keyguesta2b31d
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
Why I Love JSX!
Why I Love JSX!Why I Love JSX!
Why I Love JSX!Jay Phelps
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
How routing works in angular js
How routing works in angular jsHow routing works in angular js
How routing works in angular jscodeandyou forums
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
Resource and view
Resource and viewResource and view
Resource and viewPapp Laszlo
 
Rails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiRails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiPivorak MeetUp
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rulesnagarajhubli
 
Applications: A Series of States
Applications: A Series of StatesApplications: A Series of States
Applications: A Series of StatesTrek Glowacki
 
Paypal REST api ( Japanese version )
Paypal REST api ( Japanese version )Paypal REST api ( Japanese version )
Paypal REST api ( Japanese version )Yoshi Sakai
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Chris Alfano
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsMark
 
Architecture, Auth, and Routing with uiRouter
Architecture, Auth, and Routing with uiRouterArchitecture, Auth, and Routing with uiRouter
Architecture, Auth, and Routing with uiRouterChristopher Caplinger
 

What's hot (19)

Templates
TemplatesTemplates
Templates
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modules
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Key
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Why I Love JSX!
Why I Love JSX!Why I Love JSX!
Why I Love JSX!
 
UI-Router
UI-RouterUI-Router
UI-Router
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
How routing works in angular js
How routing works in angular jsHow routing works in angular js
How routing works in angular js
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Resource and view
Resource and viewResource and view
Resource and view
 
Rails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiRails MVC by Sergiy Koshovyi
Rails MVC by Sergiy Koshovyi
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
 
Applications: A Series of States
Applications: A Series of StatesApplications: A Series of States
Applications: A Series of States
 
Paypal REST api ( Japanese version )
Paypal REST api ( Japanese version )Paypal REST api ( Japanese version )
Paypal REST api ( Japanese version )
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
 
Architecture, Auth, and Routing with uiRouter
Architecture, Auth, and Routing with uiRouterArchitecture, Auth, and Routing with uiRouter
Architecture, Auth, and Routing with uiRouter
 

Similar to Single Page Web Apps with Backbone.js and Rails

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
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
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Introduction to Ember
Introduction to EmberIntroduction to Ember
Introduction to EmberSmartLogic
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleKaty Slemon
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)Chris Clarke
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in RailsSeungkyun Nam
 
EmberJS BucharestJS
EmberJS BucharestJSEmberJS BucharestJS
EmberJS BucharestJSRemus Rusanu
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 

Similar to Single Page Web Apps with Backbone.js and Rails (20)

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
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
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
MVS: An angular MVC
MVS: An angular MVCMVS: An angular MVC
MVS: An angular MVC
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Introduction to Ember
Introduction to EmberIntroduction to Ember
Introduction to Ember
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in Rails
 
EmberJS BucharestJS
EmberJS BucharestJSEmberJS BucharestJS
EmberJS BucharestJS
 
Angularjs
AngularjsAngularjs
Angularjs
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 

Recently uploaded

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Single Page Web Apps with Backbone.js and Rails

  • 1. SINGLE PAGE APPS WITH BACKBONE.JS & RAILS Prateek Dayal SupportBee.com
  • 2. HOW I LEARNED TO STOP WORRYING AND LOVE JAVSCRIPT!
  • 3. BUT I LOVE JQUERY!
  • 4. VANILLA JQUERY IS GREAT FOR A SIMPLE WEBSITE
  • 5. BUT YOU WANT TO BUILD A SINGLE PAGE APPLICATION
  • 6.
  • 7. Unless you’re a really fastidious coder, some sort of library to help structure large-scale JavaScript applications is important -- it’s far too easy to degenerate into nested piles of jQuery callbacks, all tied to concrete DOM elements. Jeremy Ashkenas
  • 8. ;)
  • 10.
  • 11. • All of the client logic in Javascript
  • 12. • All of the client logic in Javascript • Updates to many parts of the UI on changes to data
  • 13. • All of the client logic in Javascript • Updates to many parts of the UI on changes to data • Templating on the client side
  • 14. TO NOT GO CRAZY BUILDING IT, YOU NEED
  • 15.
  • 16. •A MVC like pattern to keep the code clean
  • 17. •A MVC like pattern to keep the code clean •Atemplating language like HAML/ERB to easily render view elements
  • 18. •A MVC like pattern to keep the code clean •Atemplating language like HAML/ERB to easily render view elements •A better way to manage events and callbacks
  • 19. •A MVC like pattern to keep the code clean •Atemplating language like HAML/ERB to easily render view elements •A better way to manage events and callbacks •A way to preserver browser’s back button
  • 20. •A MVC like pattern to keep the code clean •A templating language like HAML/ERB to easily render view elements •A better way to manage events and callbacks •A way to preserver browser’s back button • Easy Testing :)
  • 26.
  • 27.
  • 28. • 3.9 kb packed and gzipped
  • 29. • 3.9 kb packed and gzipped • Only dependency is underscore.js
  • 30. • 3.9 kb packed and gzipped • Only dependency is underscore.js • You need jQuery or Zepto for Ajax
  • 31. • 3.9 kb packed and gzipped • Only dependency is underscore.js • You need jQuery or Zepto for Ajax • Annotated source code
  • 32. MVC
  • 33. MODELS, VIEWS & COLLECTIONS
  • 34.
  • 36. MODELS • Data is represented as Models
  • 37. MODELS • Data is represented as Models • Can be Created, Validated, Destroyed & Persisted on Server
  • 38. MODELS • Data is represented as Models • Can be Created, Validated, Destroyed & Persisted on Server • Attribute changes trigger a ‘change’ event
  • 39. SB.Models.TicketSummary = Backbone.Model.extend({ id: null, subject: null, name: 'ticket', });
  • 41. COLLECTIONS •A collection of models
  • 42. COLLECTIONS •A collection of models • Triggers events like add/remove/refresh
  • 43. COLLECTIONS •A collection of models • Triggers events like add/remove/refresh • Can fetch models from a given url
  • 44. COLLECTIONS •A collection of models • Triggers events like add/remove/refresh • Can fetch models from a given url • Can keep the models sorted if you define a comparator function
  • 45. SB.Collections.TicketList = Backbone.Collection.extend({ model: SB.Models.TicketSummary, url: "/tickets", name: "tickets", initialize: function(models, options){ // Init stuff if you want } });
  • 46. VIEWS
  • 47. VIEWS • They are more like Rails’ Controllers
  • 48. VIEWS • They are more like Rails’ Controllers • Responsiblefor instantiating Collections and binding events that update the UI
  • 49. SB.Views.TicketListView = Backbone.View.extend({ tagName: 'ul', initialize: function(){ this.ticketList = new SB.Collections.TicketList; _.bindAll(this, 'addOne', 'addAll'); this.ticketList.bind('add', this.addOne); this.ticketList.bind('refresh', this.addAll); this.ticketList.bind('all', this.render); this.ticketList.fetch(); }, addAll: function(){ this.ticketList.each(this.addOne); }, addOne: function(ticket){ var view = new SB.Views.TicketSummaryView({model:ticket}); $(this.el).append(view.render().el); } });
  • 50. SB.Views.TicketSummary = Backbone.View.extend({ initialize: function(){ _.bind(this, 'render'); if(this.model !== undefined){ this.model.view = this; } }, events: { 'click': 'openTicket' }, openTicket: function(){ window.location = "#ticket/" + this.model.id; }, render: function(){ $(this.el).html(SB.Views.Templates['tickets/summary'] (this.model.toJSON())); return this; } });
  • 52. {{#ticket}} <div class="listing-cell name"> <p>{{nameOrEmail requester}} ({{replies_count}})</p> </div> <div class="listing-cell subject"> <a href="#{{id}}"> {{#unread}} <b>{{subject}}</b> {{/unread}} {{^unread}} {{subject}} {{/unread}} </a> </div> {{/ticket}}
  • 53. URLS
  • 54. URLS • Collections can have a url
  • 55. URLS • Collections can have a url • Models can have a url or they can derive it from collection’s url
  • 56. create → POST   /collection ◦ read → GET   /collection[/id] ◦ update → PUT   /collection/id ◦ delete → DELETE   /collection/id
  • 58.
  • 59. • Used for setting up the routes
  • 60. • Used for setting up the routes • You can add new routes during runtime
  • 61. SB.Controllers.AgentHome = Backbone.Controller.extend({ routes: { "": "dashboard", // http://app_url ":id": "openTicket" // http://app_url#id }, dashboard: function(){ var view = new SB.Views.TicketListView; $("#ticket").hide(); $("#list").html(view.el); $("#list").show(); }, openTicket: function(id){ var view = new SB.Views.TicketView({model : new SB.Models.Ticket({id : id})}); $("#list").hide(); $("#ticket").html(view.el); $("#ticket").show(); } });
  • 62. window.controller = new SB.Controllers.AgentHome
  • 63.
  • 64. • Initiates a new controller instance
  • 65. • Initiates a new controller instance • which matches the dashboard route
  • 66. • Initiates a new controller instance • which matches the dashboard route • and creates a instance of TicketListView
  • 67. • Initiates a new controller instance • which matches the dashboard route • and creates a instance of TicketListView • and a TicketList collection is created
  • 68.
  • 69. • TicketList collection fetches tickets and triggers the refresh event
  • 70. • TicketList collection fetches tickets and triggers the refresh event • Refresh handler renders a TicketSummary view for each ticket and adds it to the top level element
  • 71.
  • 72. • Every Ticket Summary row has an onclick handler
  • 73. • Every Ticket Summary row has an onclick handler • which changes to url to #ticket_id
  • 74. • Every Ticket Summary row has an onclick handler • which changes to url to #ticket_id • which matches the openTicket route
  • 77.
  • 78. • Youcan use as_json to customize the json responses
  • 79. • Youcan use as_json to customize the json responses • Or you can use Restfulie
  • 80. • Youcan use as_json to customize the json responses • Or you can use Restfulie • Restfulie lets you easily put links in representations too
  • 81. collection(@items, :root => "items") do |items| items.link "self", items_url items.members do |m, item| m.link :self, item_url(item) m.values { |values| values.name item.name } end end
  • 82. NOT JUST FOR API BACKED MODELS
  • 83. //window.AgentHomeController = new SB.Controllers.AgentHome; window.mainView = new SB.Views.Main; mainView.screens.add(new SB.Models.Screen({ title: 'Dashboard', href: '#dashboard', listings: [ { title: 'New Tickets', url: '/tickets?label=unanswered&replies=false' }, { title: 'Ongoing Tickets', url: '/tickets?label=unanswered&replies=true' }, { title: 'Starred Tickets', url: '/tickets?starred=true' } ] }));
  • 86. beforeEach(function(){ var ticket = new SB.Models.TicketSummary({id: 1, subject: "A Ticket", replies_count: 0, requester: {id : 1, email: 'requester@example.com', name: 'Requester', thumbnail: 'thumbnail-url'} }); this.view = new SB.Views.TicketSummary({model: ticket}); this.view.render(); }); it("should render a ticket summary correctly", function(){ expect($(this.view.el)).toHaveText(/A Ticket/); expect($(this.view.el)).toHaveText(/Requester/); }); it("should change the url on click", function(){ var currentLoc = window.location.toString(); $(this.view.el).click(); expect(window.location.toString()).toBe(currentLoc + "ticket#1"); });
  • 88. beforeEach(function(){ this.server = sinon.fakeServer.create(); this.server.respondWith("GET", "/tickets_url_mock_server", [200, { "Content-Type": "application/json" }, '{"tickets":[{"id": 1, "subject": "Ticket 1"},{"id": 2, "subject": "Ticket 2"}]}' ]); }); it("should instantiate view when tickets are fetched", function(){ var viewMock = sinon.mock(SB.Views); viewMock.expects("TicketSummary").once().returns(new Backbone.View); viewMock.expects("TicketSummary").once().returns(new Backbone.View); var view = new SB.Views.TicketList({url: "/tickets_url_mock_server"}); this.server.respond(); viewMock.verify(); expect($(view.render().el).children().length).toBe(2); });
  • 89. QUESTIONS? prateek@supportbee.com @prateekdayal http://supportbee.com

Editor's Notes

  1. Prateek Dayal, 4 years with Ruby on Rails, CoFounder SupportBee, A help desk Software for SME, like the ones using Basecamp, Also did Muziboo and run HackerStreet .. Will be talking about ... how many of you love js?\n
  2. As Douglas Crockford puts it, most widely installed language but most misunderstood or not understood at all. A lot of care for Rails but not so much for JS etc\n
  3. How many of you have used jQuery?\n
  4. If you have to select a few elements and show/hide them or apply a css property etc\n
  5. Something like Gmail. Incoming Emails affect multiple items in the view etc. \n
  6. \n
  7. Choosing a framework is like choosing Ruby on Rails. It gives you a set of conventions and a place to put things. A lot of good choices have been already made for you. \n
  8. Most of this talk is based on our experience of building SupportBee, The ticketing page is a single page app like gmail. The code is from SB\n
  9. \n
  10. Only communicate data with the server after being loaded. \n
  11. Only communicate data with the server after being loaded. \n
  12. Only communicate data with the server after being loaded. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. Created by Charles Jolley, Used in Mobile Me, iWork.com, In Strobe Inc\n
  21. Created by the founders of 280 North Inc. Used in GoMockingBird, Github Issues\n
  22. \n
  23. \n
  24. Done by Jeremy Ashkenas. He has also created coffeescript and jammit. Jammit and Backbone is part of the document cloud code. Basecamp mobile is built using Backbone\n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. You get a json of tickets and display it. And on clicking the ticket the url should be changed and ticket should be displayed\n
  32. \n
  33. \n
  34. \n
  35. Unlike a Rails&amp;#x2019; model, there is no inbuilt support for Associations yet\nYou can initialize values in the initialize method\nextend helps you setup the prototype chain so that you can again inherit from this model\n
  36. \n
  37. \n
  38. \n
  39. \n
  40. This is a collection of model SB.Models.TicketSummary\n
  41. \n
  42. \n
  43. Views also instantiate other views, which can render templates\n
  44. Event binding for click happens here\nRenders a handlebars&amp;#x2019; template\nThe model stores a reference to this view. This reference can be used to remove/update view on changes to the attribute\n
  45. \n
  46. Logicless template. Simple JSON parsing and if/else\nnameOrEmail is a helper function that you can register\n
  47. \n
  48. \n
  49. Models inherit their urls from collections. For example\n
  50. \n
  51. \n
  52. \n
  53. The openTicket route will be fired when the ticket is clicked\n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. The controller has already appended the top level element to the list element on the page and has made it visible. So when tickets are populated, they show up on the page\n
  60. The controller has already appended the top level element to the list element on the page and has made it visible. So when tickets are populated, they show up on the page\n
  61. \n
  62. \n
  63. \n
  64. \n
  65. Though you can keep this and add some parsing code to parse the json out on client side\n
  66. \n
  67. \n
  68. \n
  69. Look at Rest in Practice or Roy Fielding&amp;#x2019;s blog for more info\n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n