backbone basics with examples
DESCRIPTION
TRANSCRIPT
03 BackboneFramework AnalysisPublic Code Repository
bySergey N. Bolshchikov
http://[email protected]
New ProImage, 2012
OutlineI. Introduction
II. Dependencies
III. Componentsa. Modelb. Collectionc. View
IV. Utilitiesa. Routerb. History
V. Conclusion
Shortly: 5 things
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Shortly: 1
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Shortly: 2
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Shortly: 3
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Shortly: 4
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Shortly: 5
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Dependencies
Backbone
Underscore json2.js [jQuery]
Backbone Components
ModelBackbone model contains interactive data. It possess different useful properties and methods:
● id - modelID● idAttribute - databaseID● get(attrName) - returns attribute value● set(attrName, attrValue) - sets the value for the named attribute● clear() - removes all model attributes● toJSON() - return a copy of the model's attributes for JSON stringification● url - relative URL where the model's resource would be located on the
server● fetch() - gets the latest version of the model from the server● save() - saves the model to the DB● validate() - checks the given data before set() and save()
P.S. Almost never is predefined
var GreetingModel = Backbone.Model.extend({ // defaults specify what attributes the model should // posses upon creation defaults: { text: 'hello world' }});
var TodoModel = Backbone.Model.extend({ defaults: { id: 1000, done: false, name: 'default task', deadline: new Date() }});
Model
CollectionCollections are ordered sets of models. It can be fetched from the server. Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.● add()● remove()
Comfortable backbone built data structure over models: array and stack.● push()● pop()● unshift()● shift()
Some handy methods:● sort()● where() - filters collection by given attribute● fetch()
// Definitions// Todo Modelvar TodoModel = Backbone.Model.extend({ defaults: { id: 1000, done: false, name: 'default task', deadline: new Date() }});
// Todo Collection: ordered list of Todo modelsvar TodoCollection = Backbone.Collection.extend({ model: TodoModel});
Collection
ViewThe most disputable component in the Backbone framework.Camp I: "It's NOT a controller"Camp II: "It's a controller"Backbone Authors: "If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view."
What it does in life:● renders the template and generates html● handles user-generated events
Attributes and Methods partially of view and controller:● tagName - html tag for the generated view● $el - cached jQuery DOM selector● events: {} - hash of event● render() - rendering method
Viewvar GreetingView = Backbone.View.extend({ // every view must have a specified render method // otherwise nothing would be seen render: function() { $('p').html(this.model.get('text'));
return this; }});
var greet = new GreetingModel();
new GreetingView({model: greet}).render()
Hello world Example
Viewvar RecordView = Backbone.View.extend({ tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }}); Todo Example
Viewvar RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }});
Viewvar RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }});
Viewvar RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }});
Viewvar RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }});
Viewvar RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); }});
TemplateUnderscore templating engine by default. It's possible to connect any other.
<tr> <td><%= id %></td> <td><%= done %></td> <td><%= name %></td> <td><%= deadline %></td></tr>
● Mixes template with the data from a model● Generates html● Append is with DOM element
render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this;
}, Todo Example
var object = {};
_.extend(object, Backbone.Events);
object.on("alert", function(msg) { alert("Triggered " + msg);});
object.trigger("alert", "an event");
Event Example
EventEvents is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events.
Router & HistoryBackbone.Router provides methods for routing client-side pages, and connecting them to actions and events.
window.Router = Backbone.Router.extend({ routes: { '': 'tree', 'folder/:name': 'list' }, initialize: function() { this.headerView = new HeaderView(); $('.header').html(this.headerView.render().el); ... }, tree: function() { ... }, list: function(name) { ... }});
Performance● All modern browsers support, IE 8+
● Framework size: Backbone + Underscore = 89KB
● Application size: 330KB
Conclusion● Lightweight
● Great momentum: many project, community support
● Good documentation
● Binds to any JS library