Alexey Vasiliev

  • 6+ years experience
    • Linux and Databases administrator
    • Web and Mobile developer (Ruby, Java, JavaScript, Objective-C, C/C++)
  • Open-Source developer
    • MongodbLogger for Rails
    • SMTRails and SHTRails (shared templates for rails)
    • SkypeKit for Ruby
me

Before Backbone.js

JS templates

  • Mustache.js
  • Handlebars.js
  • Hogan.js
  • JsRender
  • Underscore.js
  • doT.js
  • MaskJS
  • others...
mustache

JS templates comparison

JS templates

Scalable JavaScript Application Architecture

toolbox

A JavaScript library is like a toolbox

International Space Station

http://www.csulb.edu/colleges/coe/ae/engr370i/ch09/chap5_2n3/image9.jpg

Web Application Module

Scalable JavaScript Application Architecture

an independent unit of functionality that is part of the total structure of a web application

Web Application Module

Scalable JavaScript Application Architecture

  • Each module has its own sandbox
  • Each part of the architecture is like a puzzle piece
  • The web application is created as a result of all parts doing their job
  • Modules must stay within their own sandboxes
  • Modules only know the sandbox
  • The sandbox also acts like a security guard
  • When modules are loosely coupled, removing a module doesn't break the others
  • The application core handles errors
  • Each part can be tested separately

Backbone.js

backbonejs.org

backbonejs

Dependency

Backbone.js

  • Underscore.js
  • json2.js
  • jQuery or Zepto
  • Template engine (if not will be use Underscore.js template)

Backbone.Events

Backbone.js

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events

Methods:

  • on
  • off
  • trigger

Backbone.View

Backbone.js

  • initialize
  • el
  • render
  • remove

this.el properties:

  • tagName
  • className
  • id
  • attributes

Backbone.Model

Backbone.js

  • initialize
  • get/set/has/unset
  • defaults
  • toJSON
  • fetch
  • save/destroy
  • validate
  • url/urlRoot
  • isNew
  • hasChanged

Backbone.Collection

Backbone.js

  • initialize
  • model
  • models
  • toJSON
  • Underscore Methods
  • add/get/remove/reset/fetch
  • at
  • length
  • comparator
  • url

Backbone.Router && Backbone.History

Backbone.js

  • initialize
  • routes
  • route
  • navigate
  • Backbone.history.start()

Naming convention

Backbone patterns

         
         
   window.App = {
       ...
   };

   App.Photo = Backbone.Model.extend({
       ...
   };
         
         
       
       
   Models:                    App.Photo
   Collections:               App.Photos
   Views:                     App.PhotoView
   Main router:               App.Router
   Custom routers:            App.SpecialRouter

   Router instance:           App.router
   View instances:            App.photoView
   Singleton model instances: App.photo
   Collection instances:      App.photos
       

Naming convention: two-level namespace

Backbone patterns

       
 Models:                    App.Models.Photo
 Collections:               App.Collections.Photos
 Views:                     App.Views.Photo
 Routes:                    App.Routes.Photo
       
     

Bootstrapping data

Backbone patterns

  <body>
      ...

      <script>
        App.photos = new Photos([
          { id: 2, name: "My dog", filename: "IMG_0392.jpg" },
          { id: 3, name: "Our house", filename: "IMG_0393.jpg" },
          { id: 4, name: "My favorite food", filename: "IMG_0394.jpg" },
          { id: 5, name: "His bag", filename: "IMG_0394.jpg" },
          ...
        ]);
      </script>
    </body>
      

Inline templates

Backbone patterns

  <script type="text/html" id="template-contact">
    <div class='contact'>
      <strong><%= name %></strong>
      <span><%= email %></span>
    </div>
  </script>
      

JST templates

Backbone patterns

  window.JST = {};

  window.JST['person/contact'] = _.template(
      "<div class='contact'><%= name %> ..."
  );

  window.JST['person/edit'] = _.template(
      "<form method='post'><input type..."
  );
      

Mixins

Backbone patterns

  mergeMixin: (view, mixin) ->
    _.defaults view::, mixin
    _.defaults view::events, mixin.events
    if mixin.initialize isnt `undefined`
      oldInitialize = view::initialize
      view::initialize = ->
        mixin.initialize.apply this
        oldInitialize.apply this
        
 mergeMixin(Test.Views.PollsShow, Test.Mixin.PollsTabs)
      

Mixins

Backbone patterns

  Test.Mixin.PollsTabs = 
  events:
   'click .poll_tab_link'              : 'pollTabOpen'
   'click .voters_tab_link'            : 'votersTabOpen'

  pollTabOpen: (e) ->
   e.preventDefault()
   Backbone.history.navigate("admin/polls/#{@model.get('id')}", true)

  votersTabOpen: (e) ->
   e.preventDefault()
   Backbone.history.navigate("admin/polls/#{@model.get('id')}/voters", true)
     

Common problems

Things outside views

Common problems

Put things in your view class code as much as possible.

Event handlers outside views

Common problems

Every time you make an event handler outside a view class, consider making a new view class.

      
      App.PhotoView = Backbone.View.extend({
        ...
      });

      // AVOID this!
      $("a.photo").click(function() { ... });
    

Zombie Views

Common problems

      
  Backbone.View::destroyView = ->
    @remove()
    @unbind()
    @onDestroyView()  if @onDestroyView
    
  class PiroPopup.Views.PopupIndex extends Backbone.View
    initialize: (options) ->
      @collection.on 'add', @render
      @collection.on 'reset', @render
      PiroPopup.globalEvents.on "update:pivotal:data", @updatePivotalState
    onDestroyView: =>
      @collection.off 'add', @render
      @collection.off 'reset', @render
      PiroPopup.globalEvents.off "update:pivotal:data", @updatePivotalState
    

Bonus

Assembly and organization of the code

Bonus

  • Asynchronous Module Definitions (AMD) by require.js
  • Sprockets: Rack-based asset packaging
  • ...

Frameworks

Bonus

HTML5 Storages

localStorage

HTML5 Storages

  • Key / value pairs - hash table
  • Persistent on page reloads
  • Avoids HTTP overhead of cookies
  • Great for storing user preferences

sessionStorage

HTML5 Storages

Same as localStorage but...

  • Lasts as long as browser is open
  • Opening page in new window or tab starts new session
  • Great for sensitive data (e.g. banking sessions)

Web SQL Database

HTML5 Storages

  • Client-side SQL database
  • Asynchronous & Synchronous* API
  • Basically wrapper around SQLite
  • Put processing (sorting, filtering, etc.) on client
  • Deprecated (!!!)

IndexedDB

HTML5 Storages

  • Best of localStorage/sessionStorage and Web SQL DB:
    • Object based data store
    • In-order retrieval by index or locate by key
  • Asynchronous & Synchronous API:
    • For the browser and for Web Workers

Application Cache

HTML5 Storages


  <html manifest="example.appcache">... </html>
     
   CACHE MANIFEST
   # Explicitly cached entries
   CACHE:
   index.html
   stylesheet.css
   images/logo.png
   scripts/main.js
   # static.html will be served if the user is offline
   FALLBACK:
   / /static.html
   # Resources that require the user to be online.
   NETWORK:
   *
      

File API

HTML5 Storages

  • File / FileList
  • FileReader
  • Drag & Drop Files

<Thank You!>

Contact information