Backbone.js

Aplicações Web com

Henrique Antonini Silvério

Front-End Developer na HE:labs

  • Twitter: @RikeSilverio
  • Blog:       blog.henriquesilver.io
  • Github:  github.com/HenriqueSilverio

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.

O que é Backbone?

"

"

backbonejs.org

Biblioteca MV*

  • Event
  • Model
  • Collection
  • View
  • Router
  • History
  • Sync

Por que escolher Backbone?

  • Pequeno e robusto.
  • Foco em manipular e consultar dados.
  • Liberdade para escolher qualquer engine de templates.
  • Não te obriga a injetar lógica da aplicação no HTML.
  • Compatível com jQuery e outros.
  • Há mais do que uma única maneira de fazer as coisas.

Quem já utiliza Backbone?

Dependências

Underscore ~ underscorejs.org

jQuery ~ jquery.com

#mimimi não use jQuery... ( http://goo.gl/QR8e13 )

Alternativas:

Lo-Dash ~ lodash.com

Zepto ~ zeptojs.com

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.

http://backbonejs.org/#Model


  var Book = Backbone.Model.extend({
      defaults: {
          title: '',
          author: ''
      }
  });

  var Book = Backbone.Model.extend({});

Definindo um Model personalizado

Instanciando e Manipulando um Model


  var book1 = new Book({ title: 'Full Stack Web Development with Backbone.js' });

  console.log( book1.get('title') );
  // => 'Full Stack Web Development with Backbone.js'

  book1.set('title', 'Backbone.js Cookbook');

  console.log( book1.get('title') );
  // => 'Backbone.js Cookbook'

  book1.set({
      title: 'Building Backbone Plugins',
      author: 'Derick Bailey'
  });

  book1.toJSON();
  // => Object {title: "Building Backbone Plugins", author: "Derick Bailey"}

Collection

Collections are ordered sets of models.

http://backbonejs.org/#Collection


  var Library = Backbone.Collection.extend({
      model: Book
  });

Declarando uma Collection personalizada

Instanciando e populando:


  var MyLibrary = new Library([
      { title: 'Developing Backbone.js Applications', author: 'Addy Osmani' },
      { title: 'Full Stack Web Development with Backbone.js ', author: 'Patrick Mulder' },
      { title: 'Building Backbone Plugins', author: 'Derick Bailey' }
  ]);

Manipulando uma Collection


  MyLibrary.at(0).toJSON();
  // => 'Developing Backbone.js Applications'

  MyLibrary.pluck('author');
  // => Array [ "Addy Osmani", "Patrick Mulder", "Derick Bailey" ]

  MyLibrary.where({ author: 'Addy Osmani' });
  // => 'Developing Backbone.js Applications'

  MyLibrary.length
  // => 3

View

Organize your interface into logical views, backed (or not) by models...

http://backbonejs.org/#View

Declarando uma View personalizada


  var BookView = Backbone.View.extend({
      tagName: 'div',

      className: 'book-item',

      events: {
          'click .open': 'openClicked'
      },

      initialize: function() {
          console.log('The View has created!');
      },

      openClicked: function(e) {
          console.log( $(e.target) );
      }
  });

  var theBook = new BookView();

  // => 'The View has created!'

View !== Template

Templates entram em ação


  var BookView = Backbone.View.extend({
      // ... tagName, className, events ...
  
      template: _.template( [
          '<b>Title:</b> <%= title %> <br>',
          '<b>Author:</b> <%= author %> <hr>' 
      ].join('') ),
  
      render: function() {
          var data = this.model.toJSON();
          this.$el.html( this.template( data ) );
          return this;
      },

      // ... initialize and other methods ...
  });

Instanciando e Renderizando uma View


  var theBookView = new BookView({ model: theBookModel });

  $('body').html( theBookView.render().el );

  var theBookModel = new Book({ 
      title: 'Backbone.Marionette.js: A Gentle Introduction', 
      author: 'David Sulc' 
  });

Surge a CollectionView

  1. Fazer um loop na `collection`
  2. Criar e renderizar uma `view` para cada model
  3. Inserir o HTML da `CollectionView` no DOM

Interessante... show me the code!


  var LibraryView = Backbone.View.extend({
      tagName: 'ul',

      className: 'books-list',

      render: function() {
          this.collection.each(function(book) {
              var bookItemView = new BookView({ model: book });
              this.$el.append( bookItemView.render().el );
          }, this);

          return this;
      }
  });

Declarando uma CollectionView

Instanciando e Renderizando uma Collection


  var BooksCollection = new Library([
      { title: 'Developing Backbone.js Applications', author: 'Addy Osmani' },
      { title: 'Full Stack Web Development with Backbone.js ', author: 'Patrick Mulder' },
      { title: 'Building Backbone Plugins', author: 'Derick Bailey' },
      { title: 'Backbone.Marionette.js: A Gentle Introduction', author: 'David Sulc' }
  ]);
  
  var theLibraryView = new LibraryView({ collection: BooksCollection });
  
  $('body').html( theLibraryView.render().el );

CollectionView exibida no browser

Events

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events.

http://backbonejs.org/#Events

Promove o baixo acoplamento entre os diversos componentes do sistema.

Ex: Views podem "escutar" eventos disparados por Models e Collections e reagir de acordo.


  var Library = Backbone.Collection.extend({

      model: Book,


      selectByCID: function(cid) {
          this.invoke('set', 'selected', false);

          var book = this.get(cid);

          if(book) {
              book.set('selected', true);
          }

          return this;
      }
  });

Modificando a Collection e a View


  var BookView = Backbone.View.extend({
      events: {
          'click': 'selectBook'
      },

      initialize: function() {
          this.listenTo( this.model, 'change:selected', this.render );
      },

      render: function() {
          var data = this.model.toJSON();

          this.$el.html( this.template( data ) );
          this.$el.toggleClass( 'selected', this.model.get('selected') );
          
          return this;
      },
      selectBook: function(e) {
          if(!this.model.get('selected')) {
              this.model.collection.selectByCID( this.model.cid );
          }
      }
  });
      // ... tagName, className, template ...

Click!

Change de View!

Router

Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events.

http://backbonejs.org/#Router

Declarando um Router

  
  var AppRouter = Backbone.Router.extend({
      routes: {
          '': 'showHome',
          'book/:id' : 'showBook'
      },
      showBook: function(id) {
          // ... get the book by id
          // ... create and render a view
          // etc
      }
  });
  
  $(function() {
      var appRouter = new AppRouter();
      Backbone.history.start();
  });

Vale a pena conferir também

Quer saber mais?

Backbone.js Resources

A curated compilation of resources to master Backbone.js development.

Aplicações Web com Backbone.js

By Henrique Silvério

Aplicações Web com Backbone.js

Slides da palestra ministrada na "Semana de TI" na faculdade Anhanguera em Bauru, dia 28/10/2015.

  • 1,155