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
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 });
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(); } });
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); }, });