Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Backbone.js - Intro

Avatar for Lucas Pelos Lucas Pelos
February 15, 2013

Backbone.js - Intro

Introdução ao client-side JS framework Backbone.js

http://backbonejs.org

Avatar for Lucas Pelos

Lucas Pelos

February 15, 2013
Tweet

More Decks by Lucas Pelos

Other Decks in Programming

Transcript

  1. Por que usar um framework JS • Dinamismo: Sem refresh's

    a cada click. ◦ Melhor user experience • Desempenho: menos requisições ao server ◦ Desonera o server ◦ Melhor tempo de resposta
  2. Por que Backbone.js? • Funciona! • Bem documentado • Amplamente

    utilizado ◦ Mais conteúdo de pesquisa (tutoriais, cursos, casos solucionados em fóruns, etc.) ▪ Aprendizado facilitado
  3. Recursos Provê: • Estrutura client-side à aplicação: organização! • Models

    para representar os dados • Views para ligar os models ao DOM • Sincroniza dados com o server • Métodos everywhere (incluindo de underscore) "Get your truth out of the DOM" - Jeremy Ashkenas
  4. Mas vale a pena! Sem Backbone: • Dados perdidos no

    DOM: <tag class="foo" data-name="name" /> $(".foo").data("name"); • Eventos desorganizados e com selectors gigantes: <a class="show-name" data-name="name"></a> <a class="show-phone" data-phone="phone"></a> $("#container .wrapper .options a.show-name").click (function(e){ alert($(this).data("name")) }); $("#container .wrapper .options a.show-phone"). click(function(e){ alert($(this).data("phone")) }); Com Backbone: • Dom limpa e dados acessíveis <tag/> this.model.name; • Eventos organizados em suas respectivas views events: { "a.show-name click": "showName", "a.show-phone click": "showPhone" } showName: function(e){ alert(this.model.name) } showPhone: function(e) { alert(this.model.phone) } • etc., etc...
  5. Model • Contem o modelo de dados • Responsável por

    executar lógica de model • Sincroniza dados com o backend var TodoItem = Backbone.Model.extend({ urlRoot: '/todos', defaults: { 'description': 'random todo', 'status': 'incomplete' }, toggleStatus: function(){ if(this.get('status') === 'incomplete'){ this.set({'status': 'complete'}); }else{ this.set({'status': 'incomplete'}); } this.save(); }
  6. var TodoView = Backbone.View.extend({ tagName: 'article', id: 'todo-view', className: 'todo',

    template: JST['templates/foo'], initialize: function(){ this.model.on('destroy', this.remove, this); }, events: { 'change input': 'toggleStatus' }, remove: function(){ this.$el.remove(); }, toggleStatus: function(){ this.model.toggleStatus(); }, render: function(){ var attributes = this.model.attributes; this.$el.html(this.template(attributes)); return this; } }); View • Renderiza o html com as informações de um instância de Model de acordo com seu Template e guarda em seu EL • Responsável pelos comportamentos da view toDo = new TodoItem; toDoView = new TodoView({ model: toDo });
  7. Template undescore.js <h3 class="<%= status %>"> <input type=checkbox <% if(status

    === "complete") print("checked") %> /> <%= description %> </h3> haml-js %h3{ :class => status } %input{ :type => "checkbox", if(status === "complete") print("checked") } = description mustache.js <h3 class="{{ status }}"> <input type=checkbox {{ if(status === "complete") print("checked") }} /> {{ description }} </h3> haml-coffee %h3{ :class => status } %input{ :type => "checkbox", if status is "complete" then print "checked" } = description
  8. Collection • Coleção de Models • Possui uma infinidade de

    métodos, incluso de underscore, como: var TodoList = Backbone.Collection.extend({ model: TodoItem, url: '/todos' initialize: function(){ this.on('remove', this.removeModel); }, hideModel: function(model){ model.destroy(); }, }); TodoList.fetch({ success: function() { alert("fetch finalizado!"); }, error: function() { alert("oops, ocorreu um erro!"); } }); add at(0) get(1) remove(todoItem1) fetch reset forEach map filter groupBy shuffle toArray indexOf
  9. Collection View • Comunica Collection e View • Delega à

    View que renderize uma 'instância' para cada Model na Collection e em seguida appenda ao próprio EL var TodoListView = Backbone.View.extend({ initialize: function(){ this.collection.on('add', this.addOne, this); this.collection.on('reset', this.addAll, this); }, addOne: function(todoItem){ var todoView = new TodoView({ model: todoItem }); todoView.render(); this.$el.append(todoView.el); }, addAll: function(){ this.collection.forEach(this.addOne, this); }, render: function(model){ this.addAll(); } });
  10. Routes • Observa e provoca mudanças na URL • Responsável

    por engatilhar a cadeia de eventos que gera a "view" e inseri-la na DOM var router = Backbone.Router.extend({ routes: { "": "index", "todos/:id": "show" }, initialize: function(){ this.todoList = new TodoList(); this.todosView = new TodoListView({ collection: this.todoList }); }, index: function(){ this.todoList.fetch({ success: function(){ this.todosView.render(); $('#app').append(this.todosView.el); } } ); }, show: function(id){ this.todoList.focusOnTodoItem(id); }, });
  11. Custom_script.js window.TodoApp = { start: function(){ new TodoRouter(); Backbone.history.start({pushState: true});

    // "pushState" to use slash instead of hash mark at url } } jQuery(function($){ TodoApp.start() });