Filipe Giusti
Roadmap
● Introdução
● Básico
○
○
○
○
○

Características
Model
View
Eventos
Router

● Além
Introdução
● Estrutura mínima para uma app decente
● Release inicial 10/2010
● MV alguma coisa
○ Porque sempre tem MV?

● Única dependência: Underscore.js
○ Para usar router e persistência: jQuery ou Zepto

● Comunidade: suficiente
Básico - Características
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.
Básico - Model
// Our basic **Todo** model has `title`, `order`, and `completed` attributes.
app.Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
},

// Toggle the `completed` state of this todo item.
toggle: function () {
this.save({completed: !this.get('completed')});
}
});
var todo1 = new app.Todo({title: 'First title', order: 1});
Básico - Model
●
●
●
●
●
●
●

initialize
get & set
id
attributes
changedAttributes
parse
toJSON
Básico - Model
● Observer pattern
● Validação
○ isValid - validation
○ Backbone.validation

● Relações
○ backbone-relational.js
○ backbone-associations
○ supermodel.js
Básico - Model
● Persistência
○
○
○
○
○
○

url - urlRoot
parse
sync - fetch - save - destroy
REST JSON
LocalStorage?
Websockets?
Básico - Model - Persistência
app.Todo = Backbone.Model.extend({
urlRoot: '/todos'
});
var todo2 = new app.Todo({title: 'First title', order: 1});
var todo3 = new app.Todo({id: 5, title: 'First title', order:
1});
todo2.url(); // "/todos"
todo3.url(); // "/todos/5"
Básico - Model - Collections
app.TodosCollection = Backbone.Collection.extend({
model: app.Todo
});
var todos = new app.TodosCollection([todo2, todo3]);
todos.length; // 2
todos.fetch();
todos.create({});
todos.add(todo2);
Backbone.sync(method, model, options);

E diversos métodos do Underscore.js.
Básico - View
● Duas partes
○ Declarativa
■ el
■ model binding
■ events
○ Procedural
■ render
■ Controller
Básico - View
app.TodoView = Backbone.View.extend({
el: '#todo',
events: {
'keypress .edit': 'updateOnEnter',
'blur .edit':
'close'
},
render: function() {
return this.$el.html( TemplateEngine.run( this.model.toJSON() ) );
},
close: function() { // executed when todo loses focus },
updateOnEnter: function( e ) { // executed on each keypress when in todo edit mode }
});
var todoView = new app.TodoView({model: todo2});
todoview.render();
Básico - Eventos
Backbone.on('event', function() {console.log('Handled Backbone event');});
Backbone.trigger('event'); // logs: Handled Backbone event

● on - off - trigger - once - listenTo
● Eventos do backbone
○ add - remove - reset - sort - change - error - route

● Custom
Básico - Router
app.TodoRouter = Backbone.Router.extend({
routes: {
"about" : "showAbout",
/* http://example.com/#about */
"todo/:id" : "getTodo",
/* http://example.com/#todo/5 */
"todos/:id/download/*documentPath" : "downloadDocument",
/* http://example.com/#todos/5/download/files/Meeting_schedule.doc */
},
showAbout: function(){
},
getTodo: function(id){
},
getTodo: function(id, path){
}
});
var myTodoRouter = new app.TodoRouter();
Backbone.history.start();
myTodoRouter.navigate('todo/5');
Além do Backbone
● Funcionalidade ausentes
○ Atributos virtuais
○ Hierarquia nas views
○ Form validation

● Marionette
○ Seta alguns padrões como o template
○ Facilita as views
■ Subview, regions, layout

● Crescimento da aplicação
Referências
● http://backbonejs.org/
● http://todomvc.com/architectureexamples/backbone/
● http://addyosmani.github.io/backbonefundamentals/

Backbone.js

  • 1.
  • 2.
  • 3.
    Introdução ● Estrutura mínimapara uma app decente ● Release inicial 10/2010 ● MV alguma coisa ○ Porque sempre tem MV? ● Única dependência: Underscore.js ○ Para usar router e persistência: jQuery ou Zepto ● Comunidade: suficiente
  • 4.
    Básico - Características Backbone.jsgives 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.
  • 5.
    Básico - Model //Our basic **Todo** model has `title`, `order`, and `completed` attributes. app.Todo = Backbone.Model.extend({ defaults: { title: '', completed: false }, // Toggle the `completed` state of this todo item. toggle: function () { this.save({completed: !this.get('completed')}); } }); var todo1 = new app.Todo({title: 'First title', order: 1});
  • 6.
    Básico - Model ● ● ● ● ● ● ● initialize get& set id attributes changedAttributes parse toJSON
  • 7.
    Básico - Model ●Observer pattern ● Validação ○ isValid - validation ○ Backbone.validation ● Relações ○ backbone-relational.js ○ backbone-associations ○ supermodel.js
  • 8.
    Básico - Model ●Persistência ○ ○ ○ ○ ○ ○ url - urlRoot parse sync - fetch - save - destroy REST JSON LocalStorage? Websockets?
  • 9.
    Básico - Model- Persistência app.Todo = Backbone.Model.extend({ urlRoot: '/todos' }); var todo2 = new app.Todo({title: 'First title', order: 1}); var todo3 = new app.Todo({id: 5, title: 'First title', order: 1}); todo2.url(); // "/todos" todo3.url(); // "/todos/5"
  • 10.
    Básico - Model- Collections app.TodosCollection = Backbone.Collection.extend({ model: app.Todo }); var todos = new app.TodosCollection([todo2, todo3]); todos.length; // 2 todos.fetch(); todos.create({}); todos.add(todo2); Backbone.sync(method, model, options); E diversos métodos do Underscore.js.
  • 11.
    Básico - View ●Duas partes ○ Declarativa ■ el ■ model binding ■ events ○ Procedural ■ render ■ Controller
  • 12.
    Básico - View app.TodoView= Backbone.View.extend({ el: '#todo', events: { 'keypress .edit': 'updateOnEnter', 'blur .edit': 'close' }, render: function() { return this.$el.html( TemplateEngine.run( this.model.toJSON() ) ); }, close: function() { // executed when todo loses focus }, updateOnEnter: function( e ) { // executed on each keypress when in todo edit mode } }); var todoView = new app.TodoView({model: todo2}); todoview.render();
  • 13.
    Básico - Eventos Backbone.on('event',function() {console.log('Handled Backbone event');}); Backbone.trigger('event'); // logs: Handled Backbone event ● on - off - trigger - once - listenTo ● Eventos do backbone ○ add - remove - reset - sort - change - error - route ● Custom
  • 14.
    Básico - Router app.TodoRouter= Backbone.Router.extend({ routes: { "about" : "showAbout", /* http://example.com/#about */ "todo/:id" : "getTodo", /* http://example.com/#todo/5 */ "todos/:id/download/*documentPath" : "downloadDocument", /* http://example.com/#todos/5/download/files/Meeting_schedule.doc */ }, showAbout: function(){ }, getTodo: function(id){ }, getTodo: function(id, path){ } }); var myTodoRouter = new app.TodoRouter(); Backbone.history.start(); myTodoRouter.navigate('todo/5');
  • 15.
    Além do Backbone ●Funcionalidade ausentes ○ Atributos virtuais ○ Hierarquia nas views ○ Form validation ● Marionette ○ Seta alguns padrões como o template ○ Facilita as views ■ Subview, regions, layout ● Crescimento da aplicação
  • 16.