SlideShare a Scribd company logo
1 of 106
MVC
[   ]
,
“   ”
BackboneJS
UnderscoreJS
MustacheJS
                        json2

    BackboneJS
  jQuery
             CacheProviderJS
UnderscoreJS
MustacheJS

    BackboneJS
BackboneJS
MustacheJS
UnderscoreJS

                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
            


                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
           


                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
            

It’s a Javascript library for writing applications
                       like....
It’s a Javascript library for writing applications
                       like....
It’s a Javascript library for writing applications
                       like....
It’s a Javascript library for writing applications
                       like....
Javascript Web
  Application
Downloads & Dependencies
Development Version (0.5.1)   41kb, Full Source with Comments
Production Version (0.5.1)  4.6kb, Packed and Gzipped




Backbone's only hard dependency is Underscore.js.
For RESTful persistence, history support via Backbone.ControllerRouter and
DOM manipulation with Backbone.View, include json2.js, and either jQuery
( > 1.4.2) or Zepto.

                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
            

Backbone.Model

• Models contain the data
• Validations,properties and
  permissions
• Manage changes to the above
var Comment = Backbone.Model.extend();
var Comment = Backbone.Model.extend();




var comment = new Comment({
    id: 83562107
    text: "       “   ”                   "
      created_at: "2011-07-03 09:04:34"
      user: {
          uid: "keso"
          id: "1000185"
          screen_name: "keso"
      }
});
Backbone.Model

• Models contain the data
• Validations,properties and
  permissions
• Manage changes to the above
comment.get('text'); //         “   ”
                             comment.set(
                                {'text':'<script>alert('xss')</script>'},
                                {silent:true}
                                );

                             comment.escape('text');
– extend
                             //
- constructor / initialize
                             &lt;script&gt;alert(&#x27xss&#x27)&lt;&#x2F;script&gt
– get
                             ;
– set
– escape
                             comment.has('city'); // false
– has
– unset
– clear                      comment.unset('text'); // trigger 'change' event
– id
– cid
– attributes                 var Comment = new Backbone.Model.extend({
– defaults                       // hash or function()
- toJSON                         defaults: {
                                     'source': 'douban.com'
                                 },
                                 initialize: function() { ... }
                             });

                             var comment = new Comment();
                             comment.get('source'); // 'douban.com'
var Comment = new Backbone.Model.extend({
                             urlRoot: '/comment'
                             initialize: function(attrs) { ... }
                         });

                         var comment = new Comment({id:123456});
–   fetch                comment.url(); // '/comment/123456'
–   save
–   destroy
–   validate
–   url
–   urlRoot              var Comment = new Backbone.Model.extend({
–   parse                    urlRoot: '/comment'
–   clone                    initialize: function(attrs) { ... },
–   isNew                    validate: function(attrs) {
–   change                       if ( attrs.text.length < 3 ) {
–   hasChanged                       return '             3     '
–   changedAttributes              }
–   previous                   }
–   previousAttributes   });

                         var comment = new Comment();
                         comment.set({text:'ok'},{
                             error: function(model,error) {
                                 alert(error);
                             }
                         });
Backbone.Model

• Models contain the data
• Validations,properties and
  permissions
• Manage changes to the above

                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
           

Backbone.Collection

• Collections are ordered sets of models
• Act on events within models
• Add, Remove, Fetch, Refresh, Create, Sort
var Comments = new Backbone.Collection.extend({

      model: Comment,

      initialize: function(models,options) {

      }

});
[
    {
        text: "        “   ”                "
        created_at: "2011-07-03 09:04:34"
        source: "douban.com"
        user: {
            city: "   "
            statuses_count: 172
            uid: "keso"
            following_count: 1688
            created_at: "2005-04-07 18:01:26"
            followers_count: 6178
            small_avatar: "http://img3.douban.com/icon/u1000185-2.jpg"
            id: "1000185"
            screen_name: "keso"
            ...
        }
        id: 83562107
    },
    {...}
    {...}
]
Backbone.Collection

• Collections are ordered sets of models
• Act on events within models
• Add, Remove, Fetch, Refresh, Create,
  Sort
App.Collections.Comments = Backbone.Collection.extend({
–   model
–   constructor / initialize         model: Comment,
–   models
                                     initialize: function(models,options) {
–   toJSON
–   Underscore Methods (25)               this.url = '/api/statuses/' + options.id + '/comments'
–   get                                           + (options.count ? '?count=' + options.count : '')
–   getByCid                                      + (options.page ? '&page=' + options.page : '');
                                          this.page = 1;
–   at
–   length                           },
–   comparator
                                     comparator: function(model) {
–   sort
                                         return -model.get('id');
–   pluck                            }
–   url
–   parse
                               });
Backbone.Collection

• Collections are ordered sets of models
• Act on events within models
• Add, Remove, Fetch, Refresh, Create,
  Sort
User = new Backbone.Model.extend({

                   initialize: function(attrs) {
                       this.url = '/users/' + attrs.id;
                   }

             });

             var user = new User({id: 2770683});

–   add      user.fetch({
–   remove       success:function(model,resp) {
–   fetch            document.title = model.get('screen_name') + '/         ';

–   reset              App.Pages.Profile = new App.Views.Profile({
                           model: model
–   create             });
                       oBody.append(App.Pages.Profile.render().el);
                   },
                   error: function(model,resp) {
                       switch (resp.status) {
                           case 404:
                               App.Pages.Error = new App.Views.Error({
                                   msg:'          '
                               });
                               oBody.append(App.Pages.Error.render().el);
                           break;
                       }
                   }
             });

                
           
 

  
                    
 
              
               
       

       
             
        
       
             

           
     
 
        
     
 
                       

       
           
      
                 
       
                   


              
 
 
 
            
             
                   

 
 
             
            

Backbone.View
Backbone.View

• A logical UI component, not just the
  template
• They are more like Rail’s Controller
• Responsible for instantiating
  Collections and binding events that
  update the UI
App.Views.Comment = Backbone.View.extend({

      className: 'comment-item',

      template: $('#comment-item-template').html(),

      events: {
          "mouseover"              : "showActions",
          "mouseout"               : "hideActions"
      },

      initialize: function() {
          _.bindAll(this, 'render');
          this.model.bind('change', this.render);
      },

      render: function() {
          $(this.el).html(Mustache.to_html(this.template, this.model.toJSON()));
          $(this.el).attr({
              'data-item-id': this.model.id,
              'data-comment-id': this.model.id
          });
          return this;
      },

      showActions: function(e) {
          this.$('.icon-delete').show();
      },
                                                                var view = new App.Views.Comment({
      hideActions: function(e) {                                    model: model
          this.$('.icon-delete').hide();
                                                                });
      }
});                                                             $('body').append(view.render().el);
Router
  Backbone.Controller

Provides methods for routing client-side URL
fragments, and connecting them to actions
and events.
App.Router.Shuo = Backbone.Router.extend({

      routes: {
          ""                                          :   "home",
          ":uid"                                      :   "profile",
          ":uid/following"                            :   "following",
          ":uid/status/:id"                           :   "permalink",
          "search/:query"                             :   "search"
      },

      initialize: function() {
          Backbone.history.start({pushState: true, root:'/'});
      },

      home: function() {
          App.Pages.Home = new App.Views.Home();
          oBody.append(App.Pages.Home.render().el);
          this.navigate('');
      },

      profile: function(uid) {
          App.Pages.Profile[uid] = new App.Views.Profile({uid: uid});
          oBody.append(App.Pages.Profile[uid].render().el);
          this.navigate(uid,true);
      },

      following: function(uid) { ...
      permalink: function(uid,id) { ...
      search: function(query) { ...
});
router.route(route, name, callback)




  initialize: function(options) {

      // Matches #page/10, passing "10"
      this.route("page/:number", "page", function(number){ ... });

      // Matches /117-a/b/c/open, passing "117-a/b/c"
      this.route(/^(.*?)/open$/, "open", function(id){ ... });

  }
Backbone.History

•   A global router (per frame) to handle
    hashchange events or pushState

• Match the appropriate route, and trigger
    callbacks
Backbone.history.start([options])



  App.Router.Shuo = Backbone.Router.extend({

        routes: {
            ""                                      :   "home",
            ":uid"                                  :   "profile",
            ":uid/following"                        :   "following",
            ":uid/status/:id"                       :   "permalink",
            "search/:query"                         :   "search"
        },

        initialize: function() {
            Backbone.history.start({pushState: true, root:'/'});
        },
  ...
Backbone.Events

◦ "add" (model, collection) — when a model is added to a collection.

◦ "remove" (model, collection) — when a model is removed from a collection.

◦ "reset" (collection) — when the collection's entire contents have been replaced.

◦ "change" (model, collection) — when a model's attributes have changed.

◦ "change:[attribute]" (model, collection) — when a specific attribute has been updated.

◦ "destroy" (model, collection) — when a model is destroyed.

◦ "error" (model, collection) — when a model's validation fails, or a save call fails on the server.

◦ "route:[name]" (router) — when one of a router's routes has matched.

◦ "all" — this special event fires for any triggered event, passing the event name as the first
   argument.
object.bind(event, callback)


  App.Views.Comment = Backbone.View.extend({

        className: 'comment-item',

        template: $('#comment-item-template').html(),

        initialize: function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },

        render: function() {
            $(this.el).html(Mustache.to_html(this.template, this.model.toJSON()));
            $(this.el).attr({
                'data-item-id': this.model.id,
                'data-comment-id': this.model.id
            });
            return this;
        }
  });
Backbone.Sync

Backbone.sync is the function that Backbone calls every time it
attempts to read or save a model to the server. By default, it uses
(jQuery/Zepto).ajax to make a RESTful JSON request. You can
override it in order to use a different persistence strategy, such as
WebSockets, XML transport, or Local Storage.
Models
Interactive Data Domain-
    specific methods
Models               Collections
Interactive Data Domain-
                           Ordered Sets of Models
    specific methods
Models               Collections
Interactive Data Domain-
                           Ordered Sets of Models
    specific methods




       Views
  Render HTML/CSS With
 Javascript templating
Models               Collections
Interactive Data Domain-
                           Ordered Sets of Models
    specific methods




       Views                    Router
  Render HTML/CSS With     Methods For Routing URL
 Javascript templating            Fragments
Models               Collections
Interactive Data Domain-
                           Ordered Sets of Models
    specific methods




       Views                    Router
  Render HTML/CSS With     Methods For Routing URL
 Javascript templating            Fragments
Models               Collections
Interactive Data Domain-
                           Ordered Sets of Models
    specific methods




       Views                    Router
  Render HTML/CSS With     Methods For Routing URL
 Javascript templating            Fragments
public/js
../libs/

    jquery.js
    backbone.js
    underscore.js
    json2.js
    mustache.js
    cacheprovider.js


../applications.js

../models/

../collections/

../views/

../controllers/
../application.js
var App = {
         Views: {},
         Router: {},
         Collections: {},
         Cache: new CacheProvider(),
         initialize: function(){
                 new App.Controllers.Shuo();
                 Backbone.history.start({pushState: true});
         }
     };




public/js/application.js
App.Routers.Shuo = Backbone.Router.extend({

       routes: {
           ""                                  :   "home",
           "comments"                          :   "comments",
           "mentions"                          :   "mentions",
           ":uid"                              :   "profile",
           ":uid/following"                    :   "following",
           ":uid/followers"                    :   "followers",
           ":uid/status/:id"                   :   "permalink",
           "search/users/:query"               :   "user_search",
           "search/:query"                     :   "search"
       },

       initialize: function() { ... },

       home: function() { ... },

       comments: function() { ... },

       mentions: function() { ... },

       profile: function(uid) { ... },

       following: function(uid) { ... },

       followers: function(uid) { ... },

       permalink: function(uid,id) { ... },

       user_search: function(query) { ... },

       search: function(query) { ... }
 });




public/js/controllers/shuo.js
public/js/models
public/js/models
public/js/models
comment.js
comment_notification.js
mention.js
recommend.js
stat.js
status.js
user.js
public/js/collections
public/js/collections
public/js/collections
comment_notifications.js
comments.js
follow_in_common.js
followers.js
following.js
following_followers_of.js
home_timeline.js
likers.js
mentions.js
recommend_list.js
resharers.js
results.js
suggestions.js
user_recommendations.js
user_results.js
user_timeline.js
users.js
public/js/views
Home
Main
Main   Dashboard
HomeHeader




  Stream
HomeHeader
             Navigation



             Following

             Followers




             Suggestion

  Stream

                ADs

               Footer
Status


Resharers




Comments
Status


Resharers




Comments
new App.Views.StreamItem();
            model: Status
 Status     model.fetch()
            this.render()




Resharers




Comments
new App.Views.StreamItem();
            model: Status
 Status     model.fetch()
            this.render()




Resharers   new App.Views.Resharers()...




Comments
new App.Views.StreamItem();
            model: Status
 Status     model.fetch()
            this.render()




Resharers   new App.Views.Resharers()...




            new App.Views.Comments()

            this.collection = new Comments({
                id: status.id

Comments    });

            this.collection.fetch()
            this.collection.add()
            this.collection.remove()
...
     <div id="page-outer">
     </div>
     ...



    <script id="status-item-template" type="text/template">...</script>
    <script id="comment-item-template" type="text/template">...</script>
    ...




template/app.html
App.Views.Permalink = Backbone.View.extend({
       el: oDoc,
       item_template: $('#permalink-item-template').html(),
       initialize: function(options) {
           _.bindAll(this, 'render', 'loadStatus', 'loadResharers', 'loadLikers', 'loadComments');
           var self = this;
           $.ajax('/api/statuses/' + options.id + '?pack=1&comment_count=50&reshare_count=14&like_count=14')
               .success(function(resp) {
                   self.status = new Status(resp.status, {id: options.id});
                   self.comments = new App.Collections.Comments(resp.comments, {id: options.id});
                   self.resharers = new App.Collections.Resharers(resp.reshare_users, {id: options.id});
                   self.loadStatus();
               })
               .error(function(resp){
                   // 404
                   }
               });
       },
       render: function() {
           return this;
       },
       loadStatus: function() {
           var view = new App.Views.StreamItem({
               model: this.status
           });
           this.loadComments();
           this.loadResharers();
           oPageContainer.prepend(view.render().el);
       },
       loadResharers: function() { ... },
       loadComments: function() { ... }
   });




public/js/views/permalink.js
App.initialize();
BackboneJS
MustacheJS
UnderscoreJS
BackboneJS
MustacheJS
UnderscoreJS
MustacheJS
{
    entities: {
        user_mentions: [],
        urls: []
    }
    text: "       “   ”                 "
    created_at: "2011-07-03 09:04:34"
    source: "douban.com"
    user: {
        city: "   "
        icon_avatar: "http://img3.douban.com/icon/ui1000185-2.jpg"
        statuses_count: 172
        uid: "keso"
        following_count: 1688
        url: ""
        created_at: "2005-04-07 18:01:26"
        description: "keso                                            http://
blog.donews.com/keso"
        followers_count: 6178
        location: "   "
        small_avatar: "http://img3.douban.com/icon/u1000185-2.jpg"
        following: false
        verified: false
        large_avatar: "http://img3.douban.com/icon/ul1000185-2.jpg"
        id: "1000185"
        screen_name: "keso"
    }
    id: 83562107
}
<script id="comment-item-template" type="text/template">
    <div class="comment-item-content" data-user-id="{{#user}}{{uid}}{{/user}}" data-item-id="{{id}}" data-
comment-id="{{id}}">
        {{#user}}
        <div class="icon">
            <a href="/#{{uid}}"><img src="{{small_avatar}}" alt="{{screen_name}}"/></a>
        </div>
        {{/user}}
        <div class="content">
            <p>
                {{#user}}
                 <a href="/#!/{{uid}}" class="to" title="{{uid}}">{{screen_name}}</a>
                {{/user}}
                 <span class="comment-time">{{timestamp}}</span>
            </p>
            <p>
                 <span class="comment-text">{{{text}}}</span>
                 <a href="" class="icon-comment" title="   "><img src="http://img3.douban.com/anduin/pics/
blank.gif"/></a>
            </p>
        </div>
    </div>
</script>
Mustache.to_html(template,data);
MustacheJS
                    


                    
 
               
           
                         

        
            
                    
       
                     

    
           
         
           
                             

            
                 
                           
 
           




            
           
         
           
       
         

Mustache 2.0 Feature Requests
BackboneJS
MustacheJS

UnderscoreJS
About Me
: It’s no big deal!
End
Thanks!

More Related Content

What's hot

Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
AoteaStudios
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
Swizec Teller
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
DrupalCampDN
 

What's hot (20)

Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Drupal Javascript for developers
Drupal Javascript for developersDrupal Javascript for developers
Drupal Javascript for developers
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 
Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
 
Single Page Apps with Drupal 8
Single Page Apps with Drupal 8Single Page Apps with Drupal 8
Single Page Apps with Drupal 8
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Rails course day 7
Rails course day 7Rails course day 7
Rails course day 7
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 

Viewers also liked

黄希彤:【无障碍访问】Margin
黄希彤:【无障碍访问】Margin黄希彤:【无障碍访问】Margin
黄希彤:【无障碍访问】Margin
taobao.com
 
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
SEO, LLC dba www.SplinternetMarketing.com
 
東海大学広報メディア学科河井ゼミ フリーペーパー2014
東海大学広報メディア学科河井ゼミ フリーペーパー2014東海大学広報メディア学科河井ゼミ フリーペーパー2014
東海大学広報メディア学科河井ゼミ フリーペーパー2014
河井 孝仁
 
Kind editor设计思路
Kind editor设计思路Kind editor设计思路
Kind editor设计思路
taobao.com
 
Telekomunikimet
TelekomunikimetTelekomunikimet
Telekomunikimet
Menaxherat
 
Presentació
PresentacióPresentació
Presentació
sbolader
 
Direct and reported speech
Direct and reported speechDirect and reported speech
Direct and reported speech
Eunice Rivera
 

Viewers also liked (20)

Epm project
Epm projectEpm project
Epm project
 
黄希彤:【无障碍访问】Margin
黄希彤:【无障碍访问】Margin黄希彤:【无障碍访问】Margin
黄希彤:【无障碍访问】Margin
 
Web rebuild
Web rebuildWeb rebuild
Web rebuild
 
Explore Peoria Competitive Analysis
Explore Peoria Competitive AnalysisExplore Peoria Competitive Analysis
Explore Peoria Competitive Analysis
 
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
Seo And Search Engine Ranking Report Splinternetmarketing.Com Internet Market...
 
Jamia Ikhwan
Jamia Ikhwan Jamia Ikhwan
Jamia Ikhwan
 
008スマートフォンによるシティプロモーションプラン研究会
008スマートフォンによるシティプロモーションプラン研究会008スマートフォンによるシティプロモーションプラン研究会
008スマートフォンによるシティプロモーションプラン研究会
 
Letters of Intent
Letters of IntentLetters of Intent
Letters of Intent
 
東海大学広報メディア学科河井ゼミ フリーペーパー2014
東海大学広報メディア学科河井ゼミ フリーペーパー2014東海大学広報メディア学科河井ゼミ フリーペーパー2014
東海大学広報メディア学科河井ゼミ フリーペーパー2014
 
My Presentation to Teradata_13 Jan 2014
My Presentation to Teradata_13 Jan 2014My Presentation to Teradata_13 Jan 2014
My Presentation to Teradata_13 Jan 2014
 
Kind editor设计思路
Kind editor设计思路Kind editor设计思路
Kind editor设计思路
 
Telekomunikimet
TelekomunikimetTelekomunikimet
Telekomunikimet
 
Lueurs Promo Eng
Lueurs Promo EngLueurs Promo Eng
Lueurs Promo Eng
 
Presentació
PresentacióPresentació
Presentació
 
LinkedIn For Car Dealers
LinkedIn For Car DealersLinkedIn For Car Dealers
LinkedIn For Car Dealers
 
Olswang 2nd Annual Construction Law Conference
Olswang 2nd Annual Construction Law ConferenceOlswang 2nd Annual Construction Law Conference
Olswang 2nd Annual Construction Law Conference
 
Belchfire Foundry Torch Search Engine Rankings
Belchfire Foundry Torch Search Engine RankingsBelchfire Foundry Torch Search Engine Rankings
Belchfire Foundry Torch Search Engine Rankings
 
Direct and reported speech
Direct and reported speechDirect and reported speech
Direct and reported speech
 
Why Software Publishers are Migrating From Certificates to Activations
Why Software Publishers are Migrating From Certificates to ActivationsWhy Software Publishers are Migrating From Certificates to Activations
Why Software Publishers are Migrating From Certificates to Activations
 
Presentatie Jaap Haas
Presentatie Jaap HaasPresentatie Jaap Haas
Presentatie Jaap Haas
 

Similar to 【前端Mvc】之豆瓣说实践

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
Frank Rousseau
 
Webinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting StartedWebinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting Started
MongoDB
 
[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool
javablend
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
Tammy Hart
 

Similar to 【前端Mvc】之豆瓣说实践 (20)

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Webinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting StartedWebinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting Started
 
[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJS
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN StackMongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 

More from taobao.com

编辑器设计U editor
编辑器设计U editor编辑器设计U editor
编辑器设计U editor
taobao.com
 
淘宝开放产品前端实践
淘宝开放产品前端实践淘宝开放产品前端实践
淘宝开放产品前端实践
taobao.com
 
广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化
taobao.com
 
第三方内容开发最佳实践
第三方内容开发最佳实践第三方内容开发最佳实践
第三方内容开发最佳实践
taobao.com
 
编辑器设计Kissy editor
编辑器设计Kissy editor编辑器设计Kissy editor
编辑器设计Kissy editor
taobao.com
 
百度前端性能监控与优化实践
百度前端性能监控与优化实践百度前端性能监控与优化实践
百度前端性能监控与优化实践
taobao.com
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践
taobao.com
 
Java script physical engine
Java script physical engineJava script physical engine
Java script physical engine
taobao.com
 
Html5环保小游戏
Html5环保小游戏Html5环保小游戏
Html5环保小游戏
taobao.com
 
阅读类Web应用前端技术探索
阅读类Web应用前端技术探索阅读类Web应用前端技术探索
阅读类Web应用前端技术探索
taobao.com
 
完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索
taobao.com
 
张平:JavaScript引擎实现
张平:JavaScript引擎实现张平:JavaScript引擎实现
张平:JavaScript引擎实现
taobao.com
 
高力:19楼现有前端架构
高力:19楼现有前端架构高力:19楼现有前端架构
高力:19楼现有前端架构
taobao.com
 
李成银:前端编译平台
李成银:前端编译平台李成银:前端编译平台
李成银:前端编译平台
taobao.com
 
钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具
taobao.com
 
张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考
taobao.com
 
刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践
taobao.com
 
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
taobao.com
 
前端Mvc探讨及实践
前端Mvc探讨及实践前端Mvc探讨及实践
前端Mvc探讨及实践
taobao.com
 

More from taobao.com (20)

编辑器设计U editor
编辑器设计U editor编辑器设计U editor
编辑器设计U editor
 
Berserk js
Berserk jsBerserk js
Berserk js
 
淘宝开放产品前端实践
淘宝开放产品前端实践淘宝开放产品前端实践
淘宝开放产品前端实践
 
广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化
 
第三方内容开发最佳实践
第三方内容开发最佳实践第三方内容开发最佳实践
第三方内容开发最佳实践
 
编辑器设计Kissy editor
编辑器设计Kissy editor编辑器设计Kissy editor
编辑器设计Kissy editor
 
百度前端性能监控与优化实践
百度前端性能监控与优化实践百度前端性能监控与优化实践
百度前端性能监控与优化实践
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践
 
Java script physical engine
Java script physical engineJava script physical engine
Java script physical engine
 
Html5环保小游戏
Html5环保小游戏Html5环保小游戏
Html5环保小游戏
 
阅读类Web应用前端技术探索
阅读类Web应用前端技术探索阅读类Web应用前端技术探索
阅读类Web应用前端技术探索
 
完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索
 
张平:JavaScript引擎实现
张平:JavaScript引擎实现张平:JavaScript引擎实现
张平:JavaScript引擎实现
 
高力:19楼现有前端架构
高力:19楼现有前端架构高力:19楼现有前端架构
高力:19楼现有前端架构
 
李成银:前端编译平台
李成银:前端编译平台李成银:前端编译平台
李成银:前端编译平台
 
钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具
 
张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考
 
刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践
 
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
 
前端Mvc探讨及实践
前端Mvc探讨及实践前端Mvc探讨及实践
前端Mvc探讨及实践
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

【前端Mvc】之豆瓣说实践

  • 1. MVC [ ]
  • 2.
  • 3.
  • 4. , “
  • 5.
  • 6.
  • 8. UnderscoreJS MustacheJS json2 BackboneJS jQuery CacheProviderJS
  • 11.
  • 12. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 13. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 14. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 15. It’s a Javascript library for writing applications like....
  • 16. It’s a Javascript library for writing applications like....
  • 17. It’s a Javascript library for writing applications like....
  • 18. It’s a Javascript library for writing applications like....
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27. Javascript Web Application
  • 28. Downloads & Dependencies Development Version (0.5.1) 41kb, Full Source with Comments Production Version (0.5.1) 4.6kb, Packed and Gzipped Backbone's only hard dependency is Underscore.js. For RESTful persistence, history support via Backbone.ControllerRouter and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( > 1.4.2) or Zepto.
  • 29. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 30. Backbone.Model • Models contain the data • Validations,properties and permissions • Manage changes to the above
  • 31.
  • 32. var Comment = Backbone.Model.extend();
  • 33. var Comment = Backbone.Model.extend(); var comment = new Comment({ id: 83562107 text: " “ ” " created_at: "2011-07-03 09:04:34" user: { uid: "keso" id: "1000185" screen_name: "keso" } });
  • 34. Backbone.Model • Models contain the data • Validations,properties and permissions • Manage changes to the above
  • 35. comment.get('text'); // “ ” comment.set( {'text':'<script>alert('xss')</script>'}, {silent:true} ); comment.escape('text'); – extend // - constructor / initialize &lt;script&gt;alert(&#x27xss&#x27)&lt;&#x2F;script&gt – get ; – set – escape comment.has('city'); // false – has – unset – clear comment.unset('text'); // trigger 'change' event – id – cid – attributes var Comment = new Backbone.Model.extend({ – defaults // hash or function() - toJSON defaults: { 'source': 'douban.com' }, initialize: function() { ... } }); var comment = new Comment(); comment.get('source'); // 'douban.com'
  • 36. var Comment = new Backbone.Model.extend({ urlRoot: '/comment' initialize: function(attrs) { ... } }); var comment = new Comment({id:123456}); – fetch comment.url(); // '/comment/123456' – save – destroy – validate – url – urlRoot var Comment = new Backbone.Model.extend({ – parse urlRoot: '/comment' – clone initialize: function(attrs) { ... }, – isNew validate: function(attrs) { – change if ( attrs.text.length < 3 ) { – hasChanged return ' 3 ' – changedAttributes } – previous } – previousAttributes }); var comment = new Comment(); comment.set({text:'ok'},{ error: function(model,error) { alert(error); } });
  • 37. Backbone.Model • Models contain the data • Validations,properties and permissions • Manage changes to the above
  • 38. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 39. Backbone.Collection • Collections are ordered sets of models • Act on events within models • Add, Remove, Fetch, Refresh, Create, Sort
  • 40. var Comments = new Backbone.Collection.extend({ model: Comment, initialize: function(models,options) { } });
  • 41. [ { text: " “ ” " created_at: "2011-07-03 09:04:34" source: "douban.com" user: { city: " " statuses_count: 172 uid: "keso" following_count: 1688 created_at: "2005-04-07 18:01:26" followers_count: 6178 small_avatar: "http://img3.douban.com/icon/u1000185-2.jpg" id: "1000185" screen_name: "keso" ... } id: 83562107 }, {...} {...} ]
  • 42. Backbone.Collection • Collections are ordered sets of models • Act on events within models • Add, Remove, Fetch, Refresh, Create, Sort
  • 43. App.Collections.Comments = Backbone.Collection.extend({ – model – constructor / initialize model: Comment, – models initialize: function(models,options) { – toJSON – Underscore Methods (25) this.url = '/api/statuses/' + options.id + '/comments' – get + (options.count ? '?count=' + options.count : '') – getByCid + (options.page ? '&page=' + options.page : ''); this.page = 1; – at – length }, – comparator comparator: function(model) { – sort return -model.get('id'); – pluck } – url – parse });
  • 44. Backbone.Collection • Collections are ordered sets of models • Act on events within models • Add, Remove, Fetch, Refresh, Create, Sort
  • 45. User = new Backbone.Model.extend({ initialize: function(attrs) { this.url = '/users/' + attrs.id; } }); var user = new User({id: 2770683}); – add user.fetch({ – remove success:function(model,resp) { – fetch document.title = model.get('screen_name') + '/ '; – reset App.Pages.Profile = new App.Views.Profile({ model: model – create }); oBody.append(App.Pages.Profile.render().el); }, error: function(model,resp) { switch (resp.status) { case 404: App.Pages.Error = new App.Views.Error({ msg:' ' }); oBody.append(App.Pages.Error.render().el); break; } } });
  • 46. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 48. Backbone.View • A logical UI component, not just the template • They are more like Rail’s Controller • Responsible for instantiating Collections and binding events that update the UI
  • 49.
  • 50. App.Views.Comment = Backbone.View.extend({ className: 'comment-item', template: $('#comment-item-template').html(), events: { "mouseover" : "showActions", "mouseout" : "hideActions" }, initialize: function() { _.bindAll(this, 'render'); this.model.bind('change', this.render); }, render: function() { $(this.el).html(Mustache.to_html(this.template, this.model.toJSON())); $(this.el).attr({ 'data-item-id': this.model.id, 'data-comment-id': this.model.id }); return this; }, showActions: function(e) { this.$('.icon-delete').show(); }, var view = new App.Views.Comment({ hideActions: function(e) { model: model this.$('.icon-delete').hide(); }); } }); $('body').append(view.render().el);
  • 51. Router Backbone.Controller Provides methods for routing client-side URL fragments, and connecting them to actions and events.
  • 52. App.Router.Shuo = Backbone.Router.extend({ routes: { "" : "home", ":uid" : "profile", ":uid/following" : "following", ":uid/status/:id" : "permalink", "search/:query" : "search" }, initialize: function() { Backbone.history.start({pushState: true, root:'/'}); }, home: function() { App.Pages.Home = new App.Views.Home(); oBody.append(App.Pages.Home.render().el); this.navigate(''); }, profile: function(uid) { App.Pages.Profile[uid] = new App.Views.Profile({uid: uid}); oBody.append(App.Pages.Profile[uid].render().el); this.navigate(uid,true); }, following: function(uid) { ... permalink: function(uid,id) { ... search: function(query) { ... });
  • 53. router.route(route, name, callback) initialize: function(options) { // Matches #page/10, passing "10" this.route("page/:number", "page", function(number){ ... }); // Matches /117-a/b/c/open, passing "117-a/b/c" this.route(/^(.*?)/open$/, "open", function(id){ ... }); }
  • 54. Backbone.History • A global router (per frame) to handle hashchange events or pushState • Match the appropriate route, and trigger callbacks
  • 55. Backbone.history.start([options]) App.Router.Shuo = Backbone.Router.extend({ routes: { "" : "home", ":uid" : "profile", ":uid/following" : "following", ":uid/status/:id" : "permalink", "search/:query" : "search" }, initialize: function() { Backbone.history.start({pushState: true, root:'/'}); }, ...
  • 56. Backbone.Events ◦ "add" (model, collection) — when a model is added to a collection. ◦ "remove" (model, collection) — when a model is removed from a collection. ◦ "reset" (collection) — when the collection's entire contents have been replaced. ◦ "change" (model, collection) — when a model's attributes have changed. ◦ "change:[attribute]" (model, collection) — when a specific attribute has been updated. ◦ "destroy" (model, collection) — when a model is destroyed. ◦ "error" (model, collection) — when a model's validation fails, or a save call fails on the server. ◦ "route:[name]" (router) — when one of a router's routes has matched. ◦ "all" — this special event fires for any triggered event, passing the event name as the first argument.
  • 57. object.bind(event, callback) App.Views.Comment = Backbone.View.extend({ className: 'comment-item', template: $('#comment-item-template').html(), initialize: function() { _.bindAll(this, 'render'); this.model.bind('change', this.render); }, render: function() { $(this.el).html(Mustache.to_html(this.template, this.model.toJSON())); $(this.el).attr({ 'data-item-id': this.model.id, 'data-comment-id': this.model.id }); return this; } });
  • 58. Backbone.Sync Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.
  • 59.
  • 61. Models Collections Interactive Data Domain- Ordered Sets of Models specific methods
  • 62. Models Collections Interactive Data Domain- Ordered Sets of Models specific methods Views Render HTML/CSS With Javascript templating
  • 63. Models Collections Interactive Data Domain- Ordered Sets of Models specific methods Views Router Render HTML/CSS With Methods For Routing URL Javascript templating Fragments
  • 64. Models Collections Interactive Data Domain- Ordered Sets of Models specific methods Views Router Render HTML/CSS With Methods For Routing URL Javascript templating Fragments
  • 65. Models Collections Interactive Data Domain- Ordered Sets of Models specific methods Views Router Render HTML/CSS With Methods For Routing URL Javascript templating Fragments
  • 67. ../libs/ jquery.js backbone.js underscore.js json2.js mustache.js cacheprovider.js ../applications.js ../models/ ../collections/ ../views/ ../controllers/
  • 69. var App = { Views: {}, Router: {}, Collections: {}, Cache: new CacheProvider(), initialize: function(){ new App.Controllers.Shuo(); Backbone.history.start({pushState: true}); } }; public/js/application.js
  • 70. App.Routers.Shuo = Backbone.Router.extend({ routes: { "" : "home", "comments" : "comments", "mentions" : "mentions", ":uid" : "profile", ":uid/following" : "following", ":uid/followers" : "followers", ":uid/status/:id" : "permalink", "search/users/:query" : "user_search", "search/:query" : "search" }, initialize: function() { ... }, home: function() { ... }, comments: function() { ... }, mentions: function() { ... }, profile: function(uid) { ... }, following: function(uid) { ... }, followers: function(uid) { ... }, permalink: function(uid,id) { ... }, user_search: function(query) { ... }, search: function(query) { ... } }); public/js/controllers/shuo.js
  • 78.
  • 79. Home
  • 80.
  • 81. Main
  • 82. Main Dashboard
  • 83.
  • 85. HomeHeader Navigation Following Followers Suggestion Stream ADs Footer
  • 86.
  • 89. new App.Views.StreamItem(); model: Status Status model.fetch() this.render() Resharers Comments
  • 90. new App.Views.StreamItem(); model: Status Status model.fetch() this.render() Resharers new App.Views.Resharers()... Comments
  • 91. new App.Views.StreamItem(); model: Status Status model.fetch() this.render() Resharers new App.Views.Resharers()... new App.Views.Comments() this.collection = new Comments({ id: status.id Comments }); this.collection.fetch() this.collection.add() this.collection.remove()
  • 92. ... <div id="page-outer"> </div> ... <script id="status-item-template" type="text/template">...</script> <script id="comment-item-template" type="text/template">...</script> ... template/app.html
  • 93. App.Views.Permalink = Backbone.View.extend({ el: oDoc, item_template: $('#permalink-item-template').html(), initialize: function(options) { _.bindAll(this, 'render', 'loadStatus', 'loadResharers', 'loadLikers', 'loadComments'); var self = this; $.ajax('/api/statuses/' + options.id + '?pack=1&comment_count=50&reshare_count=14&like_count=14') .success(function(resp) { self.status = new Status(resp.status, {id: options.id}); self.comments = new App.Collections.Comments(resp.comments, {id: options.id}); self.resharers = new App.Collections.Resharers(resp.reshare_users, {id: options.id}); self.loadStatus(); }) .error(function(resp){ // 404 } }); }, render: function() { return this; }, loadStatus: function() { var view = new App.Views.StreamItem({ model: this.status }); this.loadComments(); this.loadResharers(); oPageContainer.prepend(view.render().el); }, loadResharers: function() { ... }, loadComments: function() { ... } }); public/js/views/permalink.js
  • 98. { entities: { user_mentions: [], urls: [] } text: " “ ” " created_at: "2011-07-03 09:04:34" source: "douban.com" user: { city: " " icon_avatar: "http://img3.douban.com/icon/ui1000185-2.jpg" statuses_count: 172 uid: "keso" following_count: 1688 url: "" created_at: "2005-04-07 18:01:26" description: "keso http:// blog.donews.com/keso" followers_count: 6178 location: " " small_avatar: "http://img3.douban.com/icon/u1000185-2.jpg" following: false verified: false large_avatar: "http://img3.douban.com/icon/ul1000185-2.jpg" id: "1000185" screen_name: "keso" } id: 83562107 }
  • 99. <script id="comment-item-template" type="text/template"> <div class="comment-item-content" data-user-id="{{#user}}{{uid}}{{/user}}" data-item-id="{{id}}" data- comment-id="{{id}}"> {{#user}} <div class="icon"> <a href="/#{{uid}}"><img src="{{small_avatar}}" alt="{{screen_name}}"/></a> </div> {{/user}} <div class="content"> <p> {{#user}} <a href="/#!/{{uid}}" class="to" title="{{uid}}">{{screen_name}}</a> {{/user}} <span class="comment-time">{{timestamp}}</span> </p> <p> <span class="comment-text">{{{text}}}</span> <a href="" class="icon-comment" title=" "><img src="http://img3.douban.com/anduin/pics/ blank.gif"/></a> </p> </div> </div> </script>
  • 101. MustacheJS 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 102. Mustache 2.0 Feature Requests
  • 105. : It’s no big deal!

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. &amp;#x8C46;&amp;#x74E3;&amp;#x8BF4;&amp;#x9996;&amp;#x9875;&amp;#x622A;&amp;#x56FE; &amp;#x70B9;&amp;#x51FB;&amp;#x622A;&amp;#x56FE; &amp;#x8FDE;&amp;#x63A5;&amp;#x7EBF;&amp;#x4E0A;&amp;#x771F;&amp;#x5B9E;&amp;#x73AF;&amp;#x5883; &amp;#x6F14;&amp;#x793A;&amp;#x4EE5;&amp;#x4E0B;&amp;#x51E0;&amp;#x4E2A;&amp;#x7279;&amp;#x5F81;\n1.Single Page App &amp;#x9875;&amp;#x9762;&amp;#x8DF3;&amp;#x8F6C;&amp;#x65E0;&amp;#x5237;&amp;#x65B0;\n2.History &amp;#x7BA1;&amp;#x7406;&amp;#xFF08;url&amp;#x7279;&amp;#x70B9;&amp;#xFF09;\n3.&amp;#x57FA;&amp;#x4E8E;API&amp;#x5F00;&amp;#x53D1;\n&amp;#x6709;&amp;#x8981;&amp;#x52A8;&amp;#x753B;\n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. &amp;#x4E0A;&amp;#x622A;&amp;#x56FE; &amp;#x5355;&amp;#x6761;&amp;#x9875;&amp;#x9762; &amp;#x5373;&amp;#x53EF; \n&amp;#x56E0;&amp;#x4E3A;&amp;#x5305;&amp;#x542B;&amp;#x4E86;model &amp;#x53CA;collection&amp;#x7684;&amp;#x5B9E;&amp;#x4F8B;\n&amp;#x4F9D;&amp;#x7167;&amp;#x622A;&amp;#x56FE; &amp;#x5206;&amp;#x6790;&amp;#x51FA;&amp;#x9875;&amp;#x9762;&amp;#x4E2D;&amp;#x7684;model&amp;#x53CA;collection\n
  42. &amp;#x4E0A;&amp;#x622A;&amp;#x56FE; &amp;#x5355;&amp;#x6761;&amp;#x9875;&amp;#x9762; &amp;#x5373;&amp;#x53EF; \n&amp;#x56E0;&amp;#x4E3A;&amp;#x5305;&amp;#x542B;&amp;#x4E86;model &amp;#x53CA;collection&amp;#x7684;&amp;#x5B9E;&amp;#x4F8B;\n&amp;#x4F9D;&amp;#x7167;&amp;#x622A;&amp;#x56FE; &amp;#x5206;&amp;#x6790;&amp;#x51FA;&amp;#x9875;&amp;#x9762;&amp;#x4E2D;&amp;#x7684;model&amp;#x53CA;collection\n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. &amp;#x53EF;&amp;#x5217;&amp;#x4E3E;comments &amp;#x6216;&amp;#x8005;&amp;#x5728;status&amp;#x57FA;&amp;#x7840;&amp;#x4E0A;&amp;#x5217;&amp;#x4E3E;hometimeline&amp;#x6765;&amp;#x8BF4;&amp;#x660E;collection&amp;#x7684;&amp;#x5B9A;&amp;#x4E49;\n
  49. \n
  50. \n
  51. &amp;#x53EF;&amp;#x5217;&amp;#x4E3E;comments &amp;#x6216;&amp;#x8005;&amp;#x5728;status&amp;#x57FA;&amp;#x7840;&amp;#x4E0A;&amp;#x5217;&amp;#x4E3E;hometimeline&amp;#x6765;&amp;#x8BF4;&amp;#x660E;collection&amp;#x7684;&amp;#x5B9A;&amp;#x4E49;\n
  52. \n
  53. &amp;#x53EF;&amp;#x5217;&amp;#x4E3E;comments &amp;#x6216;&amp;#x8005;&amp;#x5728;status&amp;#x57FA;&amp;#x7840;&amp;#x4E0A;&amp;#x5217;&amp;#x4E3E;hometimeline&amp;#x6765;&amp;#x8BF4;&amp;#x660E;collection&amp;#x7684;&amp;#x5B9A;&amp;#x4E49;\n
  54. \n
  55. \n
  56. &amp;#x4E0A;&amp;#x56FE; &amp;#x5C55;&amp;#x793A;&amp;#x4EE5;&amp;#x4E0A;&amp;#x8FD9;&amp;#x90E8;&amp;#x5206;&amp;#x4EE3;&amp;#x7801;&amp;#x76F8;&amp;#x5E94;&amp;#x7684;view\n
  57. &amp;#x53EF;&amp;#x5217;&amp;#x4E3E;comments &amp;#x6216;&amp;#x8005;&amp;#x5728;status&amp;#x57FA;&amp;#x7840;&amp;#x4E0A;&amp;#x5217;&amp;#x4E3E;hometimeline&amp;#x6765;&amp;#x8BF4;&amp;#x660E;collection&amp;#x7684;&amp;#x5B9A;&amp;#x4E49;\n
  58. &amp;#x4E0A;&amp;#x622A;&amp;#x56FE; &amp;#x5355;&amp;#x6761;&amp;#x9875;&amp;#x9762; &amp;#x5373;&amp;#x53EF; \n&amp;#x56E0;&amp;#x4E3A;&amp;#x5305;&amp;#x542B;&amp;#x4E86;model &amp;#x53CA;collection&amp;#x7684;&amp;#x5B9E;&amp;#x4F8B;\n&amp;#x4F9D;&amp;#x7167;&amp;#x622A;&amp;#x56FE; &amp;#x5206;&amp;#x6790;&amp;#x51FA;&amp;#x9875;&amp;#x9762;&amp;#x4E2D;&amp;#x7684;model&amp;#x53CA;collection\n
  59. &amp;#x4E0A;&amp;#x622A;&amp;#x56FE; &amp;#x5355;&amp;#x6761;&amp;#x9875;&amp;#x9762; &amp;#x5373;&amp;#x53EF; \n&amp;#x56E0;&amp;#x4E3A;&amp;#x5305;&amp;#x542B;&amp;#x4E86;model &amp;#x53CA;collection&amp;#x7684;&amp;#x5B9E;&amp;#x4F8B;\n&amp;#x4F9D;&amp;#x7167;&amp;#x622A;&amp;#x56FE; &amp;#x5206;&amp;#x6790;&amp;#x51FA;&amp;#x9875;&amp;#x9762;&amp;#x4E2D;&amp;#x7684;model&amp;#x53CA;collection\n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. \n
  121. \n
  122. \n
  123. \n
  124. \n
  125. \n