backbone.js

49
Gran Sasso Science Institute Ivano Malavolta Backbone JS

Upload: ivano-malavolta

Post on 07-May-2015

712 views

Category:

Technology


1 download

DESCRIPTION

This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2014. http://www.ivanomalavolta.com

TRANSCRIPT

Page 1: Backbone.js

Gran Sasso Science Institute

Ivano Malavolta

Backbone JS

Page 2: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 3: Backbone.js

Why Backbone

We are building apps, not web sites

If your code is not structured:

•  it is extremely easy that your web app becomes a

big mess of HTML + CSS + JavaScript

•  maintaining each part of your app asks for a

deep analysis of ALL its aspects (logic, presentation, etc.)

•  you may waste a whole day due to a missing  <  

Page 4: Backbone.js

Why Backbone

Backbone gives you STRUCTURE

Page 5: Backbone.js

What we want to avoid

Imagine yourself trying to change

•  how a movie should be rendered in your app

•  the REST API providing info about movies

Page 6: Backbone.js

Why Backbone

From the Backbone website...

manipulate the DOM

lists of models

represent data

Page 7: Backbone.js

Why Backbone

Additionally, Backbone provides also features for:

sync

for managing how to persist models (default is via REST)

events

for managing how data and control are exchanged within your app

router

for managing the interaction flow among views

Page 8: Backbone.js

Who is using Backbone?

Page 9: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 10: Backbone.js

Events

Any object communicates with other objects via events

It gives the object the ability to bind and trigger custom named events

It is extremely useful for exchanging data and control among objects

Page 11: Backbone.js

Events

Basically, each object can:

•  listen to events

•  trigger events

Page 12: Backbone.js

Events

Two types of events:

you define your own types of event

built-in

custom

Page 13: Backbone.js

Events API

object will react to the “alert” event (the “off” function detaches the event)

event parameters

the “alert” event is fired

Page 14: Backbone.js

Events API Events methods:

on

object.on(event, callback, [context])

off

object.off([event], [callback], [context])

once

object.once(event, callback, [context])

trigger

object.trigger(event, [*args])

listenTo

object.listenTo(other, event, callback)

stopListening

object.stopListening([other], [event], [callback])

listenToOnce

object.listenToOnce(other, event, callback)

Page 15: Backbone.js

Events summary

Page 16: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 17: Backbone.js

Models

Models represent your data

Each model represents a data type in your app, together with the logic surrounding it, like:

•  persistence

•  conversions

•  validation

•  computed properties

•  access control

MVC: Notify their observers about state using the Observer pattern

Page 18: Backbone.js

Models

You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes, like:

•  getter and setter

•  id

•  constructor

•  REST-based persistence

Page 19: Backbone.js

Example of model custom method

setting an attribute

event fired when “color” changes

custom method invocation

Page 20: Backbone.js

Model constructor and attributes initialize()

it is triggered every time you create a new instance of a model

it works also for collections and views

it can take a JS object for setting also attributes

get() & set()

they are used to set and retrieve the value of certain attributes

defaults

a property named 'defaults' in your model declaration

Page 21: Backbone.js

Example

http://goo.gl/UOahsP

Page 22: Backbone.js

Model persistence

Backbone.sync

is the function that Backbone calls every time it attempts to read or save a model

By default, it uses Ajax to make a REST-ish request to a server

Resources represented as JSON strings

Page 23: Backbone.js

Sync signature

sync(method,  model,  [options])  

method

the CRUD method ("create“, "read“, "update", or "delete")

model

the model (or collection) to be synced

options

success and error callbacks, and all other jQuery request options

example of overriden sync: http://bit.ly/KWdxNN

Sync returns a jQuery XMLHttpRequest (jqXHR) object It implements the Promise interface

Page 24: Backbone.js

Sync usage

Normally you will not use the sync method directly, you will do it implicitly when you call one of these methods

Model

•  fetch: gets the most up-to-date values of the model instance

•  save: persists the model instance

•  destroy: deletes the model instance

Collection

•  fetch: gets all the models of the collection from the server

•  create: creates a model, saves it to the server and adds it to the collection

Page 25: Backbone.js

Overriding sync

You can override it in order to use a different persistence strategy, such as:

•  WebSockets

•  Local Storage

•  WebSQL

Backbone.sync is the default global function that all models use unless the models have a sync method specifically set

Page 26: Backbone.js

Models summary

Page 27: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 28: Backbone.js

Collections Collections are ordered sets of models

You can:

•  bind change events to be notified when any model in the collection has been modified

•  listen for add and remove events

•  fetch the collection from the server (or other persistence layers)

•  find models or filter collections themeselves

The model attribute of a collection represents the kind of model that can be stored in it

Any event that is triggered on a model in a collection will also be triggered on the collection directly

MVC: Notify their observers about state using the Observer pattern (same as models)

Page 29: Backbone.js

Collection example

http://goo.gl/UOahsP

Page 30: Backbone.js

Collections summary

Page 31: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 32: Backbone.js

Views

Views represent and manage the visible parts of your application

They are also used to

•  listen to interaction events

•  and react accordingly

views can be rendered at any time, and inserted into the DOM

you get high-performance UI rendering with as few reflows and repaints as possible

MVC: observe models, and update itself according to the state of the models + manage user inputs (it’s a controller, to this sense)

Page 33: Backbone.js

Interaction with the DOM All views refer to a DOM element at all times, even if they are already in the page or not

 

this.el is a reference to the DOM element, it is created from:

tagName

for example body,  ul,  span,  img  

className

class name of some element within the DOM

id

id of an element within the DOM

If none of them is specified, this.el is an empty <div>

Page 34: Backbone.js

Rendering the view

The render() method is used to update the this.el element with the new HTML

The default implementation of render() is a no-op

à you have to override it to update this.el with your HTML code

Backbone is agnostic with respect to your code in render(), however...

you are STRONGLY encouraged to use a JavaScript templating library here

Page 35: Backbone.js

View example

http://goo.gl/UOahsP

Page 36: Backbone.js

Interaction with the user

Events map “event_name selector”: callback

Events callbacks

Page 37: Backbone.js

Views summary

Page 38: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 39: Backbone.js

The router

Backbone.Router  provides methods for routing client-side pages,

and connecting them to actions and events

At a minimum, a router is composed of two main parts:

routes

an hash that pairs routes to actions

actions

JS functions triggered when certain routes are navigated

Page 40: Backbone.js

Routing

Every router contains an hash that maps routes to functions on your router

URLs fragments can also contain dynamic data via Backbone-specific URL parts:

parameter  (:param)  

match a single URL component between slashes

splat  (*fragment)  

match any number of URL components

Page 41: Backbone.js

Routing

routes map

routing functions

Page 42: Backbone.js

History

History serves as a global router to

1.  handle hashchange events

2.  match the appropriate route

3.  trigger callbacks

You should never access it directly, you just need call Backbone.history.start()  to begin monitoring hashchange events, and dispatching routes in your app

Call Backbone.history.navigate(ROUTE_NAME,  {trigger:  true}); to activate a specific route of the router  

Technically, it uses the HTML5 History API to listen to to its job

For older browsers, it uses URL hash

fragments as fallback

Page 43: Backbone.js

Router summary

Page 44: Backbone.js

Roadmap

•  Why Backbone

•  Events

•  Models

•  Collections

•  Views

•  Routers

•  Summary

Page 45: Backbone.js

Classical workflow

1.  You dig into JSON objects

2.  Look up elements in the DOM

3.  Update the HTML by hand

Page 46: Backbone.js

Backbone-based workflow

•  You organize your interface into logical views backed by models

•  Each view can be updated independently when the model changes, without having to redraw the page

You can bind your view‘s render() function to the model‘s "change” event à now everywhere that model data is displayed in the UI, it is always immediately up to date

Page 47: Backbone.js

Is Backbone real MVC?

Let’s look at the description of the Model-View-Presenter pattern on Wikipedia:

an interface defining the data to be displayed or otherwise acted upon in the user interface

passive interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data

acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view

Model

View

Presenter

Page 48: Backbone.js

References

http://backbonejs.org

Page 49: Backbone.js

+ 39 380 70 21 600 Contact

Ivano Malavolta | Gran Sasso Science Institute

iivanoo

[email protected]

www.ivanomalavolta.com