Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

33
Build spaghetti-proof web apps

description

Backbone.js est un framework javascript léger basé sur une architecture Modèle-Vue-Controlleur. Il permet de créer des application web exécutées côté client avec une communication serveur RESTful en JSON. Retour d'expérience sur son utilisation dans la conception de l'interface front de Plixee.

Transcript of Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Page 1: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Build spaghetti-proof web apps

Page 2: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

JAVASCRIPT ?

Page 3: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

JAVASCRIPT ?

Page 4: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

JAVASCRIPT ?

Page 5: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

Page 6: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

Page 7: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

• Architecture MV(C?)

Page 8: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

• Architecture MV(C?)

• Framework léger

Page 9: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

• Architecture MV(C?)

• Framework léger

• Agnostique

Page 10: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

• Architecture MV(C?)

• Framework léger

• Agnostique

• Communication RESTful

Page 11: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LA PHILOSOPHIE

• Application web monopage

• Architecture MV(C?)

• Framework léger

• Agnostique

• Communication RESTful

• Dépendance Underscore.js et jQuery

Page 12: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

HTML

Page 13: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

x nClients

HTML

Page 14: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

x nClients

HTML

Page 15: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

x nClients

HTML

Page 16: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

x nClients

HTML

+ Templating complet à chaque changement de page

Page 17: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données• Templating• i18n

Client

• Requête• Parsing HTML et affichage

LA WEB-APP CLASSIQUE

x nClients

HTML

+ Templating complet à chaque changement de page

Page 18: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données

Client

• Requête• Templating• i18n• Récupération des données

LA WEB-APP BACKBONE

JSON

Page 19: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données

Client

• Requête• Templating• i18n• Récupération des données

LA WEB-APP BACKBONE

JSON

Requêtes légères

Page 20: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

Serveur

• Logique business• Gestion des données

Client

• Requête• Templating• i18n• Récupération des données

LA WEB-APP BACKBONE

JSON

Requêtes légères Travaille pour nous

Page 21: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

L’EXEMPLE

Page 22: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES MODÈLES# Création de la classe d'un TweetTweet = Backbone.Model.extend    urlRoot: "/api/tweets"    validate: (attributes)->        if attributes.author == "" then return "Invalid author"        if attributes.text == "" or attributes.text.length > 140 then return "Invalid tweet" # Instanciation d'un nouveau TweetaTweet = new Tweet(    author: "Hugoch"    text: "Hey, I'm presenting #Backbonejs at #NWXTech5 conference.")   

 

Page 23: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES MODÈLES# Création de la classe d'un TweetTweet = Backbone.Model.extend    urlRoot: "/api/tweets"    validate: (attributes)->        if attributes.author == "" then return "Invalid author"        if attributes.text == "" or attributes.text.length > 140 then return "Invalid tweet" # Instanciation d'un nouveau TweetaTweet = new Tweet(    author: "Hugoch"    text: "Hey, I'm presenting #Backbonejs at #NWXTech5 conference.") aTweet.save()   

POST /api/tweets

Page 24: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES MODÈLES# Création de la classe d'un TweetTweet = Backbone.Model.extend    urlRoot: "/api/tweets"    validate: (attributes)->        if attributes.author == "" then return "Invalid author"        if attributes.text == "" or attributes.text.length > 140 then return "Invalid tweet" # Instanciation d'un nouveau TweetaTweet = new Tweet(    author: "Hugoch"    text: "Hey, I'm presenting #Backbonejs at #NWXTech5 conference.") aTweet.save() aTweet.save(    author: "Chuck Norris") 

POST /api/tweets

PUT /api/tweets/42

Page 25: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES MODÈLES# Création de la classe d'un TweetTweet = Backbone.Model.extend    urlRoot: "/api/tweets"    validate: (attributes)->        if attributes.author == "" then return "Invalid author"        if attributes.text == "" or attributes.text.length > 140 then return "Invalid tweet" # Instanciation d'un nouveau TweetaTweet = new Tweet(    author: "Hugoch"    text: "Hey, I'm presenting #Backbonejs at #NWXTech5 conference.") aTweet.save() aTweet.save(    author: "Chuck Norris") aTweet.destroy()

POST /api/tweets

PUT /api/tweets/42

DELETE /api/tweets/42

Page 26: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES COLLECTIONS

# Création d'une collection de tweetsTweets = Backbone.Collection.extend    model: Tweet    url: "/api/tweets" # Instanciation de la collectionsomeTweets = new Tweets()

# Récupération des Tweets sur le serveursomeTweets.fetch()

 

[    {        "id": 544102,        "author": "N_W_X",        "text": "Conférence #nwxtech5 du 24 

janvier, avec @GrieuL @nautilebleu @romainlouvet @zigazou @hugoch et @moebius_eye : amiando.com/nwxtech5"

    },    {        "id": 24454,        "author": "N_W_X",        "text": "Conférence dédiée aux tech

nos web #nwxtech5 à Rouen le 24 janvier :  amiando.com/nwxtech5"

    }]

Page 27: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES VUES

# Création d'une vue de tweetTweetView = Backbone.View.extend    tagName: "li"    className: "tweet"    render: ()->        tpl = _.template("""<h2><%-author%></h2>        <p><%-text%></p>""")        @$el.append(tpl(@model.toJSON()))        return @

# Instanciation de la collectionsomeTweets = new Tweets() # Affichage des tweets lorsqu'ils sont ajoutés à ma collectionsomeTweets.on("add",(tweet)->    view = new TweetView(        model: tweet    )    $("#tweet-list").append(view.render().el))

• Une vue = un élément du DOM

• Une vue représente un modèle

• Possibilité de mettre à jour une portion de page

Page 28: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

LES ROUTEURS# On crée la classe de routeurTweetApp = Backbone.Router.extend    routes:        "last/:num":    "showLast"        "*path":        "home"     showLast: (num)->

    # Récupération des nums derniers Tweets sur le serveur

        someTweets.fetch(            update: true            data:                limit: num        )     home: ()->        someTweets.fetch(            update: true        )# Instanciation du routeurapp = new TweetApp()

# Démarrage de l'appBackbone.history.start({pushState: true})

• Gèrent la navigation au sein de la web-app avec des URL transparentes (History API des navigateurs)

• Permettent aux utilisateurs de bookmarker des vues de l’application

Page 29: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

L’APPLICATION<html><head>    <script src="jquery.js"></script>    <script src="underscore.js"></script>    <script src="backbone.js"></script>    <script src="examples.js"></script>    <link href="stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" /></head><body>    <div id="container">        <h1>Ecrire un tweet</h1>        <div class="form-row">            <label for="new-tweet">Votre message</label>        </div>        <div class="form-row">            <textarea id="new-tweet"></textarea>        </div>        <div class="form-row right">            <button id="send-tweet">Envoyer</button>        </div>         <h1>Derniers tweets</h1>            <ul id="tweet-list">            </ul>    </div></body></html>

Insertion des vues de tweets

Page 30: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

L’APPLICATION# Création de la classe d'un TweetTweet = Backbone.Model.extend    urlRoot: "/api/tweets"    validate: (attributes)->        if attributes.author == "" then return "Invalid author"        if attributes.text == "" or attributes.text.length > 140 then return "Invalid tweet"  # Création d'une collection de tweetsTweets = Backbone.Collection.extend    model: Tweet    url: "/api/tweets" # Instanciation de la collectionsomeTweets = new Tweets() # Affichage des tweets lorsqu'ils sont ajoutés à ma collectionsomeTweets.on("add",(tweet)->    view = new TweetView(        model: tweet    )    $("#tweet-list").prepend(view.render().el)) # Création d'une vue de tweetTweetView = Backbone.View.extend    tagName: "li"    className: "tweet"    render: ()->        tpl = _.template("""<h2><%-author%></h2>        <p><%-text%></p>""")        @$el.append(tpl(@model.toJSON()))        return @ 

# On écoute le clic sur le bouton de création de tweet$(()->    $("#send-tweet").click(()->        tweet = new Tweet()        if tweet.save(            author: $("#author").val()            text: $("#new-tweet").val()        )            someTweets.add(tweet)            $("#new-tweet").val("").focus()    )) # On crée la classe de routeurTweetApp = Backbone.Router.extend    routes:        "last/:num":    "showLast"        "*path":        "home"     showLast: (num)->        # Récupération des Tweets sur le serveur        someTweets.fetch(            update: true            data:                limit: num        )     home: ()->        someTweets.fetch(            update: true        )

# Instanciation du routeurapp = new TweetApp()# Démarrage de l'appBackbone.history.start({pushState: true})

Page 31: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

EXEMPLEnwxtech.herokuapp.com

Page 32: Conférence #nwxtech5 : Introduction à Backbone.js par Hugo Larcher

CONVAINCU ?• 117 lignes de code (serveur + javascript)

• Temps réel

• 1 chargement des ressources (serveur statique), puis 300 octets par tweet

• Plugins : Backbone.Relational, LocalStorage

Utilisé par :