backbone.js
Post on 23-Jun-2015
1.324 Views
Preview:
DESCRIPTION
TRANSCRIPT
Backbone.js
Ivano MalavoltaIvano Malavolta
ivano.malavolta@univaq.it
http://www.di.univaq.it/malavolta
Roadmap
• Why Backbone
• Events• Events
• Model
• Collection
• View
• Router• Router
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 “<“
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
Intuition
Backbone gives you STRUCTURESTRUCTURESTRUCTURESTRUCTURE
Backbone
From the Backbone website...
represent data
lists of modelsmanipulatethe DOM
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
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
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
Events APIobject will react tothe “alert” event(the “off” functiondetaches the event) event parameters
the “alert” event isfired
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
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
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
Example of Modelcustom method
setting an attribute
event fired when “color” changeschanges
custom method
invocation
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
Example
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
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
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
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
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
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)
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
Example
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
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
Views
Views represent and manage the visible parts of your applicationapplication
They are also used to listen to interaction events and react accordingly
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
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>
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
Example
Roadmap
• Why Backbone
• Events• Events
• Models
• Collections
• Views
• Router• Router
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
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
Example
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
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
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
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
References
http://backbonejs.org
top related