Show Some Spine!

22
www.compete.com Show Some Spine! quick AJAX apps with Django&Backbone.js

Transcript of Show Some Spine!

w w w . c o m p e t e . c o m

Show Some Spine!quick AJAX apps with Django&Backbone.js

w w w . c o m p e t e . c o m2

An Overview of Our Evening’s Entertainment

• Ridiculously fast introduction to Backbone.js

• Building our AJAX app, a comedy in five acts

• Foundation

• The Django bits

• AJAX functionality

• Adding a delete feature and some validation

• Adding in editing

• Workshop: extend the app, ask questions, try something new

w w w . c o m p e t e . c o m3

Backbone.js at 120mph

w w w . c o m p e t e . c o m4

A First Date with Backbone.js

• AJAX apps turn into spaghetti pretty fast

• Javascript OOP is the Wild West of object systems

• Both of which spell doom for the tidy, reusable widgets

imagined by your clever UI design

• So you might be thinking of borrowing someone else’s widget

library

• But Backbone.js …

• … offers an MVC-ish framework for your front end

• … provides a basically sane object system

• … is small, reasonably easy to read, and has annotated source

• … works with a simple REST API to the backend server

w w w . c o m p e t e . c o m5

A Discreet Aside on Architecture: MVC

• MVC, aka Model/View/Controller, aka Model/View promotes

clarity of design

• Good design is the art of designing simple, flexible interfaces

• Components have well-defined responsibilities

• Components are intertwined only at interface boundaries

• MVC fits most applications, and supports good design

• The “Model” stores data and is responsible for mutating that

data

• The “View” is a display of the Model’s data

• The “Controller” manages the interactions between Model and

View

w w w . c o m p e t e . c o m6

A Discreet Aside on Architecture: REST

• REST is short for “representational state transfer”

• REST refers to the use of the HTTP protocol features to

construct an API

• For instance:

• An HTTP GET might fetch a data object from the server

• An HTTP POST could insert a new data object

• PUT can be used to update, and DELETE would naturally delete

• HTTP response codes can be used to indicate status of the request

• REST provides a very simple interface for exchanging data

• Contrast with SOAP or XML-RPC

w w w . c o m p e t e . c o m7

Backbone’s Kinda MVC

• Models and Collections manage synchronization with the

server layer

• Models represent a RESTful object

• Collections are a tidy way of managing lists of Models

• Views tie into the DOM and provide event handling semantics

• Routers can be used to map URLs or URL fragments onto

functionality

• Templates can be lifted from the DOM, or prepared in the

Javascript

w w w . c o m p e t e . c o m8

Backbone’s Models

• Models use a REST API to sync with the server

• Model or Collection is provided with a URL

• Backbone uses URL + id to perform insert, delete, update, and fetch

• Models store their state in an “attributes” object

• Models raise a variety of events:

• change whenever the attributes change

• destroy when the model is destroyed

• error when a validation fails

• Additional methods and events can be added to the basic

Model class to create a full-featured model

w w w . c o m p e t e . c o m9

Backbone’s Collections

• Collections are a grouping of Models

• Collections can be arbitrary groups, or the complete set of

available objects belonging to a particular Model subclass

• Collections raise a variety of events:

• reset whenever the whole collection is fetched or set

• will re-raise events from Models in the collection

• add and remove will fire when Models are added or removed

• Collections can define a comparator to enforce a sort order

• A comparator is a function that transforms a model into a sortable

primitive

• The sort method itself can also be overridden

w w w . c o m p e t e . c o m10

Backbone’s Views

• Views attach to a DOM element, which can be passed in, or

can be created by the view

• Views provide an events object which maps event selectors to

event handlers

• Views provide convenience features for working with JQuery

to manipulate the DOM

• Views typically couple with a Collection, a Model, or both

• Views typically use a template or a DOM fragment to

dynamically render themselves

w w w . c o m p e t e . c o m11

Underscore templates & DOM fragments

• My basic setup customizes Underscore’s templates to have

Django-like syntax

• {{ name }} interpolates the context variable name

• {% javascript = “spammy”; %} interpolates arbitrary Javascript into the

template – mostly useful for conditionals and loops and such

• Underscore templates are just Javascript strings

• Underscore compiles them into functions

• The functions accept a context object as an argument

• An alternate approach uses chunks of HTML hidden on the

page and copied out with JQuery

w w w . c o m p e t e . c o m12

Putting it all together

w w w . c o m p e t e . c o m13

A Sample Backbone + DjangoApp

w w w . c o m p e t e . c o m14

Address: the app

• On Github: https://github.com/ggerrietts/vertebrate-django

• Built around a simple contact record: first, last, email

• Displays all contacts in the database

• Allows entry of a new contact

• Validates entered email addresses against a simple regex

• Enables deletion of contacts from the database

• Permits (inline) editing of the records in the database

w w w . c o m p e t e . c o m15

/common

/common/static/{js,css,ext}

/common/templates

/common/views.py

/common/models.py

/address

/address/static/{js,css,img}

/address/templates

/address/views.py

/address/models.py

/address/admin.py

/urls.py

/settings.py

• Common provides

framework elements

• Third-party components

• Master template

• “Library” classes

• Address is our specific

application

• App-specific media

• App template(s)

• Actual models & views

App layout

w w w . c o m p e t e . c o m16

The app skeleton

• The app skeleton provides some frameworky infrastructure

• common/views.py maps a REST API onto Django models

• common/models.py has the default serialization mechanics

• common/static/ext has our third-party dependencies

• common/static/js has some customization code

• The skeleton also has a master template and master CSS file

w w w . c o m p e t e . c o m17

Django-emails, the Django app

• address/models.py defines our contact record

• address/views.py is a simple REST-powered view

• address/templates/address/contact.html lays a foundation to

build our app on

• This branch also adds a CSS file and some images

• We add an admin.py file to power up the admin interface

• And we builds out the global urls.py

w w w . c o m p e t e . c o m18

Backbone-emails, a functional app

• All the interesting bits here happen in Javascript, but one of

our files sees changes

• address/templates/address/contact.html is refactored to

instantiate our Backbone objects when the page loads

• address/static/js/address.js is where the magic happens

• The app doesn’t have much going on yet, but it does work!

w w w . c o m p e t e . c o m19

Add-delete, a deeper look at Backbone

• Backbone models support validation, which we add to our

ContactModel

• Validation on ContactModel

• Error handler on the view

• Error events versus error callback

• Backbone views do easy event delegation. We put an event

on our ContactModelView to catch the click on the delete

button

• Entry in events hash

• Click handler

• Destroy handler

w w w . c o m p e t e . c o m20

Add-edit, making all those pieces dance

• Add an extra “edit row” to our template

• Hide by default, and toggle whether edit or display is activated

• Handle submit of edit row

• Process edit and save changes to the model

• Close the edit after submit

• Handle validation errors

w w w . c o m p e t e . c o m21

Epilogue: Extending the app

w w w . c o m p e t e . c o m22

Group up and pick a project or two!

• Add validation – require fields, require capitalization?

• Add additional fields

• Enforce uniqueness on email address

• Enforce Django validation (and propagate errors properly)

• Refactor the Underscore templates to live in the DOM

• Or for the truly ambitious

• Add tracking of communications with a contact

• Permit multiple sets of contact information per name

• Add a “detailed view” panel for additional attributes

• Or a personally motivated project