backbone.js
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/malavoltaTRANSCRIPT
![Page 2: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/2.jpg)
Roadmap
• Why Backbone
• Events• Events
• Model
• Collection
• View
• Router• Router
![Page 3: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/3.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/4.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/5.jpg)
Intuition
Backbone gives you STRUCTURESTRUCTURESTRUCTURESTRUCTURE
![Page 6: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/6.jpg)
Backbone
From the Backbone website...
represent data
lists of modelsmanipulatethe DOM
![Page 7: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/7.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/8.jpg)
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
![Page 9: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/9.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/10.jpg)
Events APIobject will react tothe “alert” event(the “off” functiondetaches the event) event parameters
the “alert” event isfired
![Page 11: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/11.jpg)
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
![Page 12: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/12.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/13.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/14.jpg)
Example of Modelcustom method
setting an attribute
event fired when “color” changeschanges
custom method
invocation
![Page 15: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/15.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/16.jpg)
Example
![Page 17: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/17.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/18.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/19.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/20.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/21.jpg)
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
![Page 22: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/22.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/23.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/24.jpg)
Example
![Page 25: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/25.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/26.jpg)
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
![Page 27: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/27.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/28.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/29.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/30.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/31.jpg)
Example
![Page 32: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/32.jpg)
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
![Page 33: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/33.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/34.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/35.jpg)
Example
![Page 36: Backbone.js](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/36.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/37.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/38.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/39.jpg)
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](https://reader033.vdocuments.us/reader033/viewer/2022060118/55896cdad8b42aed5a8b4688/html5/thumbnails/40.jpg)
References
http://backbonejs.org