Share
Embed
Transcript
21 slides
-
• MV* • Separação Lógica entre camadas • Evita código
macarronico WTF Backbone? -
Backbone.Model var Product = Backbone.Model.extend({ urlRoot: '/products' }); GET /products/:id
PUT /products POST /products/:id DELETE /products/:id -
Backbone.Model var Product = Backbone.Model.extend({ urlRoot: '/products' }); GET /products/:id
PUT /products POST /products/:id DELETE /products/:id fetch save save destroy -
Backbone.View var ProductItemView = Backbone.View.extend({ tagName: 'li', className: 'product', initialize:
function () { this.model.on('change', this.render, this); }, render: function () { this.$el.html(this.model.get('name')); return this; } }); -
Collection View var ProductsView = Backbone.View.extend({ tagName: 'ul', className: 'products',
initialize: function () { this.collection.on('add', this.addOne, this); this.collection.on('reset', this.addAll, this); }, render: function () { return this; }, addAll: function () { this.$el.html(''); this.collection.forEach(this.addOne, this); }, addOne: function (product) { var view = new ProductItemView({ model: product }); this.$el.append(view.render().el); } }); -
Backbone.Router var App = new (Backbone.Router.extend({ routes: { 'products' :
'products' }, products: function () { var collection = new Products, view = new ProductsView({collection: collection}); $('#container').html(view.render().el); collection.fetch(); }, start: function () { Backbone.history.start({pushState: true}); } })); -
Backbone.Router var App = new (Backbone.Router.extend({ routes: { 'products' :
'products' }, products: function () { var collection = new Products, view = new ProductsView({collection: collection}); $('#container').html(view.render().el); collection.fetch(); }, start: function () { Backbone.history.start({pushState: true}); } })); Com pushState ativado: ‘/products’ Sem pushState: ‘#products’ -
Backbone.Router var App = new (Backbone.Router.extend({ routes: { 'products' :
'products' }, products: function () { var collection = new Products, view = new ProductsView({collection: collection}); $('#container').html(view.render().el); collection.fetch(); }, start: function () { Backbone.history.start({pushState: true}); } })); $(function () { App.start(); }); -
Views Handling Events var ProductsView = Backbone.View.extend({ ... events: {
'click li' : 'open' } ... open: function (event) { //Código para abrir o registro } }); -
$(function () { $.getJSON('/products.json', function (data) { var list =
$('<ul></ul>').attr('class', 'products'); $.each(data, function (product) { var item = $('<li></li>'). attr('class', 'product'). val(product.name); list.append(item); }); $('#container').html(list); }); $('#container').on('click', 'ul.products li', function () { //Lógica de renderizar a página do produto }); });