Client-side MVC with Backbone.js

99

description

- Why Backbone - Architecture - Real World - Tips & Tricks - Extras

Transcript of Client-side MVC with Backbone.js

Page 1: Client-side MVC with Backbone.js
Page 2: Client-side MVC with Backbone.js

Client-side MVC with Backbone.js

Page 3: Client-side MVC with Backbone.js

igloolab.com@iloveigloo

michele.berto.li@MicheleBertoli

igloo

Page 4: Client-side MVC with Backbone.js

Lago di Garda

Page 5: Client-side MVC with Backbone.js

Lago di Garda

jQueryHTML5 UPLOADER

igloolab.com/jquery-html5-uploader

KOALAkoooala.com POMODORO WEBAPP

pomodorowebapp.com

JOBBERONEjobberone.com

SHARP SQUAREigloolab.com/sharpsquare

Page 6: Client-side MVC with Backbone.js

Agenda

Page 7: Client-side MVC with Backbone.js

Questions

Why Backbone.js

Architecture

Real World

Tips & Tricks

Extras

14:00 min

05:00 min

06:00 min

04:00 min

05:00 min

06:00 min

Page 8: Client-side MVC with Backbone.js

Why Backbone.js

Page 9: Client-side MVC with Backbone.js

Why Backbone.js

From server-side to client-side

Page 10: Client-side MVC with Backbone.js

Why Backbone.js

From server-side to client-side

We need efficient tools

Page 11: Client-side MVC with Backbone.js

Why Backbone.js

jQuery is cool but…

Page 12: Client-side MVC with Backbone.js

Why Backbone.js

jQuery is cool but…

We have to store object informations intothe DOM

var list = ""; $.each(data, function (index, value) { list += "<li id=\"item-" + value.Id + "\">" + value.Name + "</li>"; }); $("ul").append(list);

Page 13: Client-side MVC with Backbone.js

Why Backbone.js

jQuery is cool but…

We have to store object informations intothe DOM

var list = ""; $.each(data, function (index, value) { list += "<li id=\"item-" + value.Id + "\">" + value.Name + "</li>"; }); $("ul").append(list);

Page 14: Client-side MVC with Backbone.js

Why Backbone.js

$.getJSON("/Items", function (data) { var list = ""; $.each(data, function (index, value) { list += "<li id=\"item-" + value.Id + "\">" + value.Name + "</li>"; }); $("ul").append(list);

$("li").click(function () { var $this = $(this); var id = $this.attr("id").replace("item-", ""); $.post("/Items", { id: id }, function () { $this.fadeOut(function () { $this.remove(); }); }); });

});

jQuery is cool but…

jQuery callback hell

Page 15: Client-side MVC with Backbone.js

Why Backbone.js

jQuery is cool but…

jQuery callback hell

$.getJSON("/Items", function (data) { var list = ""; $.each(data, function (index, value) { list += "<li id=\"item-" + value.Id + "\">" + value.Name + "</li>"; }); $("ul").append(list);

$("li").click(function () { var $this = $(this); var id = $this.attr("id").replace("item-", ""); $.post("/Items", { id: id }, function () { $this.fadeOut(function () { $this.remove(); }); }); });

});

Page 16: Client-side MVC with Backbone.js

Why Backbone.js

“It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks.”

Page 17: Client-side MVC with Backbone.js

Why Backbone.js

So, what do we need?

• Abstraction.

• Decoupling UI from Data.

• No more callbacks.

Page 18: Client-side MVC with Backbone.js

Why Backbone.js

• A RESTful service based data layer.

• Events (to keep UI and data up-to-date).

• A template engine.

• A solid routing system.

• All the above things wrapped into a lightweight JavaScript framework.

So, what do we need? (More practically)

Page 19: Client-side MVC with Backbone.js

Why Backbone.js

It exists and it’s called: Backbone.js

Page 20: Client-side MVC with Backbone.js

Architecture

Page 21: Client-side MVC with Backbone.js

Architecture

Jeremy Ashkenas

Oct 13th, 2010

Page 22: Client-side MVC with Backbone.js

Architecture

http://documentcloud.github.com/backbone

https://github.com/documentcloud/backbone

@documentcloud

#documentcloud on IRC

https://groups.google.com/forum/#!forum/backbonejs

Page 23: Client-side MVC with Backbone.js

Architecture

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.

Page 24: Client-side MVC with Backbone.js

Architecture

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.

Page 25: Client-side MVC with Backbone.js

Architecture

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.

Page 26: Client-side MVC with Backbone.js

Architecture

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.

Page 27: Client-side MVC with Backbone.js

Architecture

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.

Page 28: Client-side MVC with Backbone.js

Architecture

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.

Page 29: Client-side MVC with Backbone.js

Architecture

Dependencies:

• jQuery or Zepto

• Underscore.js

• Json2.js

Page 30: Client-side MVC with Backbone.js

Architecture

MVC

Model / Collection

Template (View)

View (Controller)

Router

Page 31: Client-side MVC with Backbone.js

MVC

Model / Collection

Template (View)

View (Controller)

Router

Architecture

Page 32: Client-side MVC with Backbone.js

MVC

Model / Collection

Template (View)

View (Controller)

Router

Architecture

Page 33: Client-side MVC with Backbone.js

MVC

Model / Collection

Template (View)

View (Controller)

Router

Architecture

Page 34: Client-side MVC with Backbone.js

Architecture

MVC

Model / Collection

Template (View)

View (Controller)

Router

Page 35: Client-side MVC with Backbone.js

Model• Representing data (auto-generated).

• Handling persistence. • Throws events.

• Reusable.

Page 36: Client-side MVC with Backbone.js

Architecture

• Fetch

• Save (new) • Save

• Destroy

/url

/url /url/id

/url/id

HTTP GET

HTTP POSTHTTP PUT

HTTP DELETE

Model / Collection - View - Template - Router - Utilities

Model

Page 37: Client-side MVC with Backbone.js

Architecture

var Item = Backbone.Model.extend({ idAttribute: “Id”, urlRoot: “/Items” });

Model / Collection - View - Template - Router - Utilities

Page 38: Client-side MVC with Backbone.js

Architecture

var item = new Item(); item.set({ Name: “Igloo” }); // trigger change item.save(); // trigger sync

Model / Collection - View - Template - Router - Utilities

Page 39: Client-side MVC with Backbone.js

Architecture

• extend

• constructor / initialize

• get

• set

• escape

• has

• unset

• clear

• id

• idAttribute

• cid

• attributes

• defaults

• toJSON

• fetch

• save

• destroy

• validate

• isValid

• url

• urlRoot

• parse

• clone

• isNew

• change

• hasChanged

Model / Collection - View - Template - Router - Utilities

Model• changedAttributes

• previous

• previousAttributes

Page 40: Client-side MVC with Backbone.js

Collection• A list of models.

• Underscore methods.

Page 41: Client-side MVC with Backbone.js

Architecture

var Items = Backbone.Collection.extend({ model: Item, url: "/Items" });

Model / Collection - View - Template - Router - Utilities

Page 42: Client-side MVC with Backbone.js

Architecture

var items = new Items(); items.fetch(); // trigger reset

Model / Collection - View - Template - Router - Utilities

Page 43: Client-side MVC with Backbone.js

Architecture

items.comparator = function(item) { return item.get("Name"); };

Model / Collection - View - Template - Router - Utilities

Page 44: Client-side MVC with Backbone.js

Architecture

Collection

• extend

• model

• constructor / initialize

• models

• toJSON

• add

• remove

• get

• getByCid

• at

• length

• comparator

• sort

• pluck

• url

• parse

Model / Collection - View - Template - Router - Utilities

• etch

• eset

• create

Page 45: Client-side MVC with Backbone.js

Architecture

Collection

Model / Collection - View - Template - Router - Utilities

• forEach (each)

• map

• reduce (foldl, inject)

• reduceRight (foldr)

• find (detect)

• filter (select)

• reject

• every (all)

• some (any)

• include

• invoke

• max

• min

• sortBy

• groupBy

• sortedIndex

• shuffle

• toArray

• size

• first

• initial

• rest

• last

• without

• indexOf

• lastIndexOf

• isEmpty

• chain

Page 46: Client-side MVC with Backbone.js

View• Manipulates the DOM.

• Delegates DOM events.• Has a Model / Collection.

Page 47: Client-side MVC with Backbone.js

Architecture

View

Model / Collection - View - Template - Router - Utilities

View (Model)

View (Collection)

Page 48: Client-side MVC with Backbone.js

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Model / Collection - View - Template - Router - Utilities

Page 49: Client-side MVC with Backbone.js

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Model / Collection - View - Template - Router - Utilities

Page 50: Client-side MVC with Backbone.js

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Model / Collection - View - Template - Router - Utilities

Page 51: Client-side MVC with Backbone.js

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Model / Collection - View - Template - Router - Utilities

Page 52: Client-side MVC with Backbone.js

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Model / Collection - View - Template - Router - Utilities

Page 53: Client-side MVC with Backbone.js

var ItemView = Backbone.View.extend({ tagName: "li", render: function () { this.$el.text(this.model.get("Name")); return this; } });

Architecture

var ListView = Backbone.View.extend({ el: $("ul"), initialize: function () { this.collection.bind("reset", this.render, this); }, render: function () { this.collection.each(this.addItem, this); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }); this.$el.append(itemView.el); itemView.render(); } });

Model / Collection - View - Template - Router - Utilities

Page 54: Client-side MVC with Backbone.js

Architecture

var items = new Items(); var listView = new ListView({ collection: items }); items.fetch();

Model / Collection - View - Template - Router - Utilities

Page 55: Client-side MVC with Backbone.js

Architecture

View• $ (jQuery or Zepto)

• render

• remove

• make

• delegateEvents

• undelegateEvents

• extend

• constructor / initialize

• el

• $el

• setElement

• attributes

Model / Collection - View - Template - Router - Utilities

Page 56: Client-side MVC with Backbone.js

Template (Underscore.js)

Compiles JavaScript templates into functions that can be evaluated for rendering.

• Mustache • jQuery-tmpl

Page 57: Client-side MVC with Backbone.js

ArchitectureModel / Collection - View - Template - Router - Utilities

<script type="text/template" id="item-template"> <li> <%= Name %> </li> </script>

Page 58: Client-side MVC with Backbone.js

Architecture

var ItemView = Backbone.View.extend({ … template: _.template($("#item-template").html()), ... render: function () { this.$el.html(this.template(this.model.toJSON())); return this; } … });

Model / Collection - View - Template - Router - Utilities

Page 59: Client-side MVC with Backbone.js

• Maps urls to function.

• Enable history / bookmarking.

Router

Page 60: Client-side MVC with Backbone.js

ArchitectureModel / Collection - View - Template - Router - Utilities

var AppRouter = Backbone.Router.extend({ routes: { "": "initialize“ }, initialize: function () { … } });

Page 61: Client-side MVC with Backbone.js

Architecture

window.AppRouter = Backbone.Router.extend({ routes: { "": "loadInvoices", "/add": "addInvoice", "/show/:id": "showInvoice", "/edit/:id": "editInvoice“ }, loadInvoices: function () { … }, addInvoice: function () { … }, showInvoice: function (id) { … }, editInvoice: function (id) { … } });

Model / Collection - View - Template - Router - Utilities

Page 62: Client-side MVC with Backbone.js

Router

Architecture

• extend

• routes

• constructor / initialize

• route

• navigate

Model / Collection - View - Template - Router - Utilities

Page 63: Client-side MVC with Backbone.js

Utilities• History • Sync• Utility

Page 64: Client-side MVC with Backbone.js

Architecture

Router View

Model /Collection

Template

DataSource

Page 65: Client-side MVC with Backbone.js

Real World

Page 66: Client-side MVC with Backbone.js

Real World

• .NET RESTful Web Services / MS SQL • Backbone.js

Polar management• Smart invoicing web application

Technologies

Page 67: Client-side MVC with Backbone.js

Real World

Polar management

Page 68: Client-side MVC with Backbone.js

Real World

Page 69: Client-side MVC with Backbone.js

Real World

Page 70: Client-side MVC with Backbone.js

Real World

Polar management

window.AppRouter = Backbone.Router.extend({ routes: { … "/modifica/:id": "editInvoice“ }, editInvoice: function (id) { … } });

Page 71: Client-side MVC with Backbone.js

Polar management

Real World

window.AppRouter = Backbone.Router.extend({ routes: { … "/modifica/:id": "editInvoice“ }, editInvoice: function (id) { … } });

Page 72: Client-side MVC with Backbone.js

Real World

Koala

• NET RESTful Web Services / RavenDB • Backbone.js • Highcharts.js

Technologies

• Social media analytics

Page 73: Client-side MVC with Backbone.js

Real World

Page 74: Client-side MVC with Backbone.js

Real World

Page 75: Client-side MVC with Backbone.js

Real World

window.Logs = Backbone.Collection.extend({ model: Log, url: "/Data", comparator: function (log) { return log.get("Date"); }, sum: function (field) { return this.reduce(function (memo, log) { return memo + log.get(field); }, 0); } });

Koala

Page 76: Client-side MVC with Backbone.js

Real World

window.Logs = Backbone.Collection.extend({ model: Log, url: "/Data", comparator: function (log) { return log.get("Date"); }, sum: function (field) { return this.reduce(function (memo, log) { return memo + log.get(field); }, 0); } });

Koala

Page 77: Client-side MVC with Backbone.js

Real World

window.Logs = Backbone.Collection.extend({ model: Log, url: "/Data", comparator: function (log) { return log.get("Date"); }, sum: function (field) { return this.reduce(function (memo, log) { return memo + log.get(field); }, 0); } });

Koala

Page 78: Client-side MVC with Backbone.js

Real World

Linkedin

Page 79: Client-side MVC with Backbone.js

Real World

FourSquare

Page 80: Client-side MVC with Backbone.js

Real World

WunderKit

Page 81: Client-side MVC with Backbone.js

Real World

Groupon

Page 82: Client-side MVC with Backbone.js

Real World

Basecamp

Page 83: Client-side MVC with Backbone.js

3

Tips & Tricks

Page 84: Client-side MVC with Backbone.js

Tips & Tricks

idAttribute: “id”

// CouchDB idAttribute: “_id”

// .NET idAttribute: “Id”

idAttribute

Page 85: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

Page 86: Client-side MVC with Backbone.js

Tips & Tricks

var Invoice = Backbone.Model.extend({ idAttribute: “Id” }); var Invoices = Backbone.Collection.extend({ model: Invoice, url: "/Invoices" });

Related Models

Page 87: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

Page 88: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

Page 89: Client-side MVC with Backbone.js

Tips & Tricks

var InvoiceDetail = Backbone.Model.extend({ idAttribute: “Id” }); var InvoiceDetails = Backbone.Collection.extend({ model: InvoiceDetail, url: "/InvoiceDetails“ });

Related Models

Page 90: Client-side MVC with Backbone.js

Tips & Tricks

var Invoice = Backbone.Model.extend({ idAttribute: "Id", initialize: function () { this.setInvoiceDetails(); }, setInvoiceDetails: function () { this.set({ InvoiceDetails: new InvoiceDetails(this.get("InvoiceDetails")) }); } });

Related Models

Page 91: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

Page 92: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

Page 93: Client-side MVC with Backbone.js

Tips & Tricks

Related Models

var Invoice = Backbone.Model.extend({ idAttribute: "Id", initialize: function () { this.setInvoiceDetails(); this.bind("sync", this.setInvoiceDetails); }, setInvoiceDetails: function () { this.set({ InvoiceDetails: new InvoiceDetails(this.get("InvoiceDetails")) }); } });

Page 94: Client-side MVC with Backbone.js

Extras

Page 95: Client-side MVC with Backbone.js

Extras

Plugins

• Backbone-Nested

• Backbone.Memento

• Backbone.Validations

• Backbone.localStorage

• backbone.couchdb.js

• …

https://github.com/documentcloud/backbone/wiki/Extensions%2C-Plugins%2C-Resources

Page 96: Client-side MVC with Backbone.js

Extras

• http://sproutcore.com (Apple/iCloud)

• http://knockoutjs.com

• http://emberjs.com

• http://batmanjs.org (Shopify)

Page 97: Client-side MVC with Backbone.js

Extras

• http://www.igloolab.com/downloads/backbone-cheatsheet.pdf

Cheat Sheet

Page 98: Client-side MVC with Backbone.js

Backbone.js

-

• Lightweight • Powerful • Code is clean (and maintainable)

+

• Too verbose (for small applications)

Page 99: Client-side MVC with Backbone.js

3Lago di Garda

Questions ?

Graziewww.igloolab.com

@iloveigloo