backbone.js

Post on 15-Jan-2015

408 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

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ênciaapp.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 - Collectionsapp.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 - Viewapp.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 - EventosBackbone.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 - Routerapp.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

top related