backbone.js

40
Backbone.js Ivano Malavolta Ivano Malavolta [email protected] http://www.di.univaq.it/malavolta

Upload: gran-sasso-science-institute

Post on 23-Jun-2015

1.324 views

Category:

Education


0 download

DESCRIPTION

Backbone.jsThis presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy). http://www.di.univaq.it/malavolta

TRANSCRIPT

Page 1: Backbone.js

Backbone.js

Ivano MalavoltaIvano Malavolta

[email protected]

http://www.di.univaq.it/malavolta

Page 2: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Model

• Collection

• View

• Router• Router

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 + big mess of html + big mess of html + big mess of html + csscsscsscss

+ + + + javascriptjavascriptjavascriptjavascript

• maintaining each part of your app asks• maintaining each part of your app asks

for a deepdeepdeepdeep analysisanalysisanalysisanalysis ofofofof ALL ALL ALL ALL itsitsitsits aspectsaspectsaspectsaspects

(logic, presentation, etc.)

• you may waste a whole day due to

a missing “<“

Page 4: 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 5: Backbone.js

Intuition

Backbone gives you STRUCTURESTRUCTURESTRUCTURESTRUCTURE

Page 6: Backbone.js

Backbone

From the Backbone website...

represent data

lists of modelsmanipulatethe DOM

Page 7: Backbone.js

Backbone (continued)

Backbone provides also features for:

• syncsyncsyncsync– for managing how to persist models

• eventseventseventsevents– for managing how data and control are exchangedwithin your appwithin your app

• routerrouterrouterrouter– for managing the interaction flow among views

Page 8: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Models

• Collections

• Views

• Router• Router

Page 9: Backbone.js

Events

EventsEventsEventsEvents is a module that can be mixed in to any object

It gives the object the ability to bindbindbindbind and triggertriggertriggertriggercustom named events

It is extremely useful for exchanging data and controlamong objectsamong objects

Page 10: Backbone.js

Events APIobject will react tothe “alert” event(the “off” functiondetaches the event) event parameters

the “alert” event isfired

Page 11: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Models

• Collections

• Views

• Router• Router

Page 12: Backbone.js

Models

Models Models Models Models represent your data

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

• persistence• conversions• validations• validations• computed properties• access control

Page 13: Backbone.js

Models

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

• getter and setter

• id

• constructor• constructor

• JSON persistance

Page 14: Backbone.js

Example of Modelcustom method

setting an attribute

event fired when “color” changeschanges

custom method

invocation

Page 15: Backbone.js

Model Constructor and Attributes

• initializeinitializeinitializeinitialize()()()()– it is triggered every time you create a new instance of a – it is triggered every time you create a new instance of a model

– it works also for collections and views

– it can take an JS object for setting also attributes

• getgetgetget() & set()() & set()() & set()() & set()– they are used to set and retrieve the value of certain– they are used to set and retrieve the value of certainattributes

• defaultsdefaultsdefaultsdefaults– a property named 'defaults' in your model declaration

Page 16: Backbone.js

Example

Page 17: Backbone.js

Sync

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

By default, it uses Ajax to make a RESTful JSON request to a server

Page 18: Backbone.js

Sync Usage

Usually, youyouyouyou willwillwillwill notnotnotnot useuseuseuse the the the the syncsyncsyncsync methodmethodmethodmethod directlydirectlydirectlydirectly, youwill it implicitly when you call one of these methods

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

– save: persists the model instance

– destroy: deletes the model instance

• Collections– fetch

– create

Page 19: Backbone.js

Sync

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

• WebSockets

• Local Storage

• WebSQL

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

Page 20: Backbone.js

Sync Signature

The method signature of Backbone.sync is

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

sync(method, model, [options])

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

• modelmodelmodelmodel: the model (or collection) to be synced

• optionsoptionsoptionsoptions – success and error callbacks, and all other jQuery request options

Page 21: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Models

• Collections

• Views

• Router• Router

Page 22: 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 layer)

Page 23: Backbone.js

Collections

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

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

Page 24: Backbone.js

Example

Page 25: Backbone.js

Collection Methods

Methods on collections include:

• fetchfetchfetchfetch: gets all the models of a collection• createcreatecreatecreate: creates a new model within the collection• resetresetresetreset: updates the collection in bulk• addaddaddadd: adds a model to the collection• removeremoveremoveremove: removes a model from the collection• removeremoveremoveremove: removes a model from the collection• atatatat: returns a specific model from the collection• sortsortsortsort: sorts the collection

Page 26: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Models

• Collections

• Views

• Router• Router

Page 27: Backbone.js

Views

Views represent and manage the visible parts of your applicationapplication

They are also used to listen to interaction events and react accordingly

Page 28: Backbone.js

Views

All views have a DOM element at all times, even if they are already in the page or notare already in the page or not

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

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

Page 29: Backbone.js

View DOM element

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

• tagNametagNametagNametagName– for example body, ul, span, img

• classNameclassNameclassNameclassName– class name of some element within the DOM

• idididid• idididid– id of an element within the DOM

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

Page 30: Backbone.js

View DOM render()

The render() method is used to update the this.elelement with the new HTMLelement with the new HTML

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

� you have to override it to create the new HTML

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

you are STRONGLYSTRONGLYSTRONGLYSTRONGLY encouraged to use a Javascript templating library here

Page 31: Backbone.js

Example

Page 32: Backbone.js

Roadmap

• Why Backbone

• Events• Events

• Models

• Collections

• Views

• Router• Router

Page 33: Backbone.js

Router

Backbone.RouterBackbone.RouterBackbone.RouterBackbone.Router provides methods for routingroutingroutingrouting client-side pages, and connecting them to actions and connecting them to actions and connecting them to actions and connecting them to actions and side pages, and connecting them to actions and connecting them to actions and connecting them to actions and connecting them to actions and eventseventseventsevents

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

• routesroutesroutesroutes• routesroutesroutesroutes– an hash that pairs routes to actions

• actionsactionsactionsactions– JS functions triggered when certain routes are navigated

Page 34: Backbone.js

Routes

It is an hash that maps URLs to functions on your It is an hash that maps URLs to functions on your It is an hash that maps URLs to functions on your It is an hash that maps URLs to functions on your routerrouterrouterrouterrouterrouterrouterrouter

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

• parameter• parameter– match a single URL component between slashes

• splat– match any number of URL components

Page 35: Backbone.js

Example

Page 36: Backbone.js

History

HistoryHistoryHistoryHistory serves as a global router to

1. handle hashchange events1. handle hashchange events

2. match the appropriate route

3. trigger callbacks

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

Page 37: Backbone.js

Summary: Classical Workflow

1. You dig into JSON objects

2. look up elements in the DOM2. look up elements in the DOM

3. update the HTML by hand

JS scripts

DOM events

DOM updates

DOM

you

data sources

interacts

data & events

updates

Page 38: Backbone.js

Summary: BackboneYou organize your interface into logical views backed by models

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

Model

Viewinteracts

DOM events

model updates

model events

DOM updates

DOM

Model

Routerdata

sources

model updates

sync routing

updates

Page 39: Backbone.js

Summary: Backbone

You can bind your view‘s render() 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 is displayed in the UI, it is always immediately up to date

Page 40: Backbone.js

References

http://backbonejs.org