2. Backbone.js
● Problem?
● Solution!
● Model
● Collection
● Template
● View
● API synchronization
3. Problem?
● Standard JavaScript libraries let you
quickly build apps
but...
● You get no structure
● Nested callbacks
● Everything is tied to DOM elements
4. Solution = Backbone.js
● Well structured
– Models
– Collections
– Views
● Lightweight
● Deep linking (Routers)
● Effortless API synchronization
● Open source
5. Model
"Models are the heart of any JavaScript
application, containing the interactive data
as well as a large part of the logic
surrounding it: conversions, validations,
computed properties, and access control."
~ The creators of Backbone.js
6. Model
Person = Backbone.Model.extend({
defaults: { name: "Newborn Baby", age: 0 },
validate: function(attributes) {
if(attributes.name == "") {
return "Really? A person without a name?";
}
},
initialize: function() {
this.bind("change:name", function() {
console.log("New name: " + this.get("name"));
});
}
});
var person = new Person({ name: "John", age: 28 });
7. Collection
var p1 = new Person({ name: "John", age: 25 });
var p2 = new Person();
var p2_name = p2.get("name"); // = Newborn Baby
p2.set({ name: "Jane", age: p1.get("age") });
People = Backbone.Collection.extend({
model: Person,
comparator: function(item) {
return item.get("name");
}
});
var twins = new People([ p1, p2 ]);
10. API synchronization
...with a RESTful API:
Addresses = Backbone.Collection.extend({
Done!
url: 'api/addresses'
});
var addresses = new Addresses();
addresses.fetch();