5. Model
● Manage the data for an application
● When model changes -> it'll typically notify
its View that a change has occurred so that
they may react accordingly.
● var Shape = Backbone.Model.extend({
defaults: { x:50,
y:50,
width:150,
height:150,
color:'black' }
});
6. Collection
● Group of models together
● managing models in groups allows us to
write application logic based on notification
from the group, should any model it contains
change
● var Document = Backbone.Collection.extend({
model: Shape
});
7. Views
● are a visual representation of models that
present a filtered view of their current state.
● var ShapeView = Backbone.View.extend();
● Templating
○ Handlebars.js
○ Matache
8. Controllers
● are an intermediary between models and
views which are classically responsible for
two tasks:
○ update the view when the model changes
○ and update the model when the user manipulates
the view
● C is change from MVC framework to other*
● Does Backbone.js have Controllers? *
● Router*
○ main purpose is to translate URL requests into
application states.
9. MVP
● P
○ All invocations from the
View delegate directly to
Presenter.
○ The Presenter is also
decoupled directly from
the View and talks to it
through an interface.
○ This is to allow mocking
of the View in a unit test.
10. MVC or MVP
● MVP
○ is generally used most often in applications where it’
s necessary to reuse as much presentation logic as
possible.
○ Applications with very complex views and a great
deal of user interaction may find that MVC doesn’t
quite fit the bill here as solving this problem may
mean heavily relying on multiple controllers.
○ MVP may be more easy to automatically unit test
than MVC*
11. MVC, MVP and Backbone.js
● Is Backbone MVC or MVP?
12. What is backbone?
● Created by Jeremy
Ashkenas, creator of
CoffeeScript, Docco and
Underscore.js.
● Client-side development
framework
● MV* framework
● can be easily tested using
third-party toolkits such as
Jasmine or QUnit
14. Why backbone?
● Organize your code in (model - collection-
views)
○ No more Free-hanging
○ No more Unrelated blocks of code
● no more complex UI synch code
● RESTful
● Decouple the DOM from your page's data
18. 1. Model
● Store data
● attributes hash
● fire events when data is changed
● (function($){
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
})(jQuery);
19. cont. Model
● defaults: There are times when you want
your model to have a set of default values.
This can be set using a property called
defaults in your model.
○ var item = new Item();
○ var item = new Item({"part1": "welcome", "part2": "to c9" });
● constructor / initialize : When creating an instance
of a model, you can pass in the initial values of
theattributes, which will be set on the model. If you
define an initialize function, it will be invoked when the
model is created.
20. cont. Model
● Getters & Setters
○ Model.get()
■ var item = new Item();
console.log("//Get Model attributesnpart1: ", item.get("part1"));
○ Model.set()
■ item.set("part1", "welcome");
console.log("//After set model by new valuesnpart1: ", item.get
("part1"))
○ Model.attributes
■ console.log("Model Attributes", item.attributes);
○ Model.toJSON()
■ console.log("Model Attributes as JSON", item.toJSON());
21. cont. Model
● Listening for changes to your model
○ initialize: function(){
console.log('this model has been initialized');
this.on("change:part1", function(model){
var part1 = this.get("part1");
console.log("My part1 has been changed to.. " + part1);
});
},
setPart1: function(newPart){
this.set("part1", newPart);
}
22. cont. Model
● Validation
○ Backbone supports model validation through Model.
validate(), which allows checking the attribute values
for a model prior to them being set.
○ Validation functions can be as simple or complex as
necessary. If the attributes provided are valid,
nothing should be returned from .validate(). If they
are invalid, a custom error can be returned instead.
○ validate: function(attribs){
if(attribs.part3 === undefined){
return "Remember to set a part3!";
}}
○ item.set({ "part3": "hi" });
23. 2. Collection
● sets of Models
var List = Backbone.Collection.extend({
model: Item
});
● Getters and Setters
○ Collection.models :
■ itemlist = new List([item, item2]);
■ console.log(itemlist.models);
○ get : collection.get(id) Get a model from a
collection, specified by id.
■ console.log(itemlist.at(1).get("part1"));
24. cont. Collectio
○ remove: Remove a model (or an array of models)
from the collection
■ itemlist.remove(item);
console.log("After remove item",itemlist.models) ;
● Underscore utility functions (28)
○ Collections
■ sortBy: Returns a sorted copy of list
● sort :function(){ return this.sortBy(function (item) { return item.get("part1").
toLowerCase();
}); }
○ Arrays
○ Function
○ Object
○ Utility
○ Chaining
25. 3. View
● Display Data
● Description of a model
● Render data with template
● Respond to model data changes
● Act on user input entries
● var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
}});
26. cont. View
● What is el?
○ el is basically a reference to a DOM element and all
views must have one.
○ It allows for all of the contents of a view to be
inserted into the DOM at once
○ There are two ways to attach a DOM element to a
view:
i. the element already exists in the page
ii. a new element is created for the view and added
manually by the developer.
○ If the element already exists in the page:-
● el: '#elem_id',
● // OR
● el: document.getElementById( 'body' )
27. cont. View
○ If you want to create a new element for your view,
set any combination of the following view’s
properties: tagName, id and className.
A new element will be created for you by the
framework and a reference to it will be available
at the el property.
● tagName: 'p', // required, but defaults to 'div' if not set
className: 'container', // optional, you can assign multiple
classes to this property like so 'container
id: 'header', // optional
● The above code creates the DOMElement below but doesn’t
append it to the DOM.
<p id="header" class="container"></p>
28. initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
// remember: every function that uses 'this' as the current object
should be in here
this.collection = new List();
this.collection.bind('add', this.appendItem);
// collection event binder
this.counter = 0;
this.render();
},
render: function(){
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){
// in case collection is not empty
self.appendItem(item);
}, this);
},
29. cont. View
● initialize(): method is called when a new
instance of a model is created. Its use is optional
● render(): is an optional function that defines
the logic for rendering a template
○ $(this.el).append("<button id='add'>Add list item</button>");
○ $(this.el).append("<ul></ul>");
30. addItem: function(){
this.counter++;
var item = new Item();
item.set({
part2: item.get('part2') + this.counter // modify item defaults
});
this.collection.add(item); // add item to collection; view is
updated via event 'add'
},
appendItem: function(item){
$('ul', this.el).append("<li>"+item.get('part1')+" "+item.get
('part2')+"</li>");
}
});
var listView = new ListView();
31. 4. Routers
● used to help manage application state and
for connecting URLs to application events.
● This is achieved using hash-tags with URL
fragments, or using the browser’s pushState
and History API
● var GalleryRouter = Backbone.Router.extend({
routes: { "about" : "showAbout",
"items/:id" : "getItem",},
showAbout: function(){ },
getItem: function(id){
console.log("You are trying to reach item " + id);
},
32. Backbone.history
● Backbone.history is where Backbone stores
all of the places you’ve been.
● This is necessary in order to not break the
back button in your browser.
● The Backbone.history.start() method will
simply tell Backbone that it’s OK to begin
monitoring all hashchange events as follows:
○ Backbone.history.start();