SlideShare a Scribd company logo
1 of 32
BACKBONE.JS
Javascript framework intro




                        // based on Artjom Kurapov’s experience on
                                               Weekendee project
Problem
        (JS) code becomes messy
    Dynamic HTML (done any dynamic tables with jquery?)
Lots of 0-level UI functions
Solution
Object Oriented code = more focus on what, less on function
Higher level of abstraction = more layers
Enter JS frameworks
              Hello ladies..
Details please
   View — Collection — Model ( MVC, right? )
   Lightweight (6kb ≠ Extjs 1mb)
   JSON, pure REST (remember PUT/DELETE http headers?)
   Event driven (bang your head here)
SO its not a
 DOM manipulation lib (jquery, prototype, mootools)
 Animation kit
 Control suite (jquery UI, ExtJS)
Core Concepts
   Models — storage
   Collections — grouping
   Views — rendering
   Router — navigation
Bird’s eye view
Models
Primitive model
Now can be used as
me.set({someAttr:’Today!’});
me.save();


… but we can handle saving too …
.save({success:.., error:..});


… and tie it to some view …
SomeEventView.model
Actual model definition
Weekendee.Models.Event = Backbone.Model.extend({

      defaults: {
      },

      url: function () {
          if (this.id === undefined) this.id = '';
          return base_url + 'event/' + this.id;
      },

      validate: function (attrs) {
          if (attrs.text != null && $.trim(attrs.text) == '') {
               return t('event.error_empty');
          }
      }
});
Kohana controller in back
  public function action_index() {
            $requestMethod = $this->request->method();

            switch ($requestMethod) {
                      case 'GET':
                                 $eventId = $this->request->param('id');
                                 $this->_read();
                                 break;

                      case 'POST':

                                 $eventId = $this->request->param('id');

                                 if (!$eventId) {
                                           $this->_create();
                                 }
                                 else if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
                                           $httpMethodOverride = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
                                           if ($httpMethodOverride == "PUT") {
                                                      $this->_update();
                                           }
                                           else if ($httpMethodOverride == "DELETE") {
                                                      $this->_delete();
                                           }
                                 }

                                 break;
                      default:
                                 $this->_read();
            }
  }
Views
Primitive view
View events
Views – most important
   .extend
   events:{}
   .el
   .initialize() -> .render() -> .template()
_js templating
Actual view definition
Weekendee.Views.EventComment = Backbone.View.extend({
     className: 'comment clearAfter’,
     template: _.template($('#event-comment-template').html()),
     events: {'click a.removeComment': 'removeComment’},
     render: function () {
          var template_vars = this.model.toJSON();
          template_vars.text = replaceURLWithHTMLLinks(template_vars.comment);
          $(this.el).html(this.template(template_vars));
          $(this.el).attr('data-id', this.model.get('commentId'));
          $('h3', $(this.el)).css('color', this.model.get('color'));
          return this;
     },
     removeComment: function () {
          this.model.destroy();
          this.remove();
     }
});
Collections
Primitive collections
Actual collection definition
Weekendee.Collections.FriendRequests = Backbone.Collection.extend({
    page: 1,

      url: function () {
          return base_url + 'user/list_friend_requests/?page=' + this.page;
      },

      parse: function (resp) {
          this.page = resp.page;
          this.perPage = resp.per_page;
          this.total = resp.total;
          return resp.models;
      }
});
Actual collection creation
Weekendee.Views.ContactsPage = Backbone.View.extend({
    "el": "#contacts",
    show: function () {
         this.friendRequestsView = new Weekendee.Views.FriendRequests({
                  collection: new Weekendee.Collections.FriendRequests()
             });
…
Actual collection view
Weekendee.Views.FriendRequests = Backbone.View.extend({
     'el': '#friend_requests’,
     initialize: function () {
          this.collection.bind('reset', this.reset, this);
          this.collection.fetch();
     },
     reset: function (FriendRequestWrapper) {
          var me = this;
          $('.contacts-body', $(this.el)).html('');

          $.each(FriendRequestWrapper.models, function (i, model) {
               var view = new Weekendee.Views.FriendRequest({
                    model: new Weekendee.Models.Contact(model)
               });
               $('.contacts-body', $(me.el)).append(view.render().el);
          });
      }
});
Router
Primitive router
Actual router
Weekendee.Routers.AppRouter = Backbone.Router.extend({
      routes: {
            "/week": "week", // #/week
            "/": "week",
            "": "week",
            "/contacts": "contacts", // #/week
            //"/week/:year/:week": "week",// #/week/2011/13
            //"/week/:startdate": "week", // #/week/2011-10-07
            "/event/:id": "event", // #/event/123
            "/event/:id/:uid": "event", // external facebook links
            "/vibe/:id": "vibe", // #/vibe/123
            "/invite/:id": "invite", // #/vibe/123
            "/*": "initial”
      },
      week: function () {
            Weekendee.WeekPage.reload();
            Weekendee.WeekPage.show();
            //Weekendee.WeekPage.setSlider(sliderState);
            Weekendee.ContactsPage.hide();
      },
Mine field
Problems
 Event propagation - loss of bind context
var me = this;
var comment = new Weekendee.Models.EventComment(commentModel);
me.collection.add(comment);
comment.bind('destroy', me.removeComment,   me);


 Hard to debug if you’re being dumb – model is
  not printable
  userModel.set(‘name’,’Dr. Who?’);
Problems
 Lack of documentation / best practices…
Problems
 (because of) big variety of connectivity
  combinations:
  X Models (update/get updated by)
  Y Views with
  Z Collections
 And thus.. How to bind stuff correctly?
 Manage collection of views?

More Related Content

What's hot

Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumnameEmanuele Quinto
 
Data20161007
Data20161007Data20161007
Data20161007capegmail
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...allilevine
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingSamuel ROZE
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsRebecca Murphey
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created itPaul Bearne
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
WordPress Capabilities Magic
WordPress Capabilities MagicWordPress Capabilities Magic
WordPress Capabilities Magicmannieschumpert
 

What's hot (20)

PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 
Data20161007
Data20161007Data20161007
Data20161007
 
20. CodeIgniter edit images
20. CodeIgniter edit images20. CodeIgniter edit images
20. CodeIgniter edit images
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
 
Matters of State
Matters of StateMatters of State
Matters of State
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
BVJS
BVJSBVJS
BVJS
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event Sourcing
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
WordPress Capabilities Magic
WordPress Capabilities MagicWordPress Capabilities Magic
WordPress Capabilities Magic
 

Viewers also liked

Dvd digipaks examples
Dvd digipaks  examplesDvd digipaks  examples
Dvd digipaks examplesTRUDY
 
Energy efficiency presentation
Energy efficiency presentationEnergy efficiency presentation
Energy efficiency presentationAustin Energy
 
What could you do with XinSpring?
What could you do with XinSpring?What could you do with XinSpring?
What could you do with XinSpring?MintTwist
 
Social Media: Am I Doing it Right?
Social Media: Am I Doing it Right?Social Media: Am I Doing it Right?
Social Media: Am I Doing it Right?Woodland Park Zoo
 
Begbroke transfer - making the most of your website
Begbroke transfer - making the most of your websiteBegbroke transfer - making the most of your website
Begbroke transfer - making the most of your websiteObergine
 
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς Levadia Library
 
Redis varnish js
Redis varnish jsRedis varnish js
Redis varnish jsiliakan
 
XinSpring the system for marketing teams
XinSpring the system for marketing teamsXinSpring the system for marketing teams
XinSpring the system for marketing teamsMintTwist
 
Home Study Questionnaire Joint
Home Study Questionnaire JointHome Study Questionnaire Joint
Home Study Questionnaire JointJonathan's Place
 
Visualization of evolutionary cascades of messages using force-directed graphs
Visualization of evolutionary cascades of messages using force-directed graphsVisualization of evolutionary cascades of messages using force-directed graphs
Visualization of evolutionary cascades of messages using force-directed graphsАртём Курапов
 
Video analysis - Paramore
Video analysis - ParamoreVideo analysis - Paramore
Video analysis - ParamoreChristina Worby
 
Incident Management
Incident ManagementIncident Management
Incident Managementbhawik
 
Architetti, Shamir by EF Cinisello
Architetti, Shamir by EF CiniselloArchitetti, Shamir by EF Cinisello
Architetti, Shamir by EF CiniselloShamir By EF
 
Th k 2 yang dinyatakan lulus kab.Kuningan
Th k 2 yang dinyatakan lulus kab.KuninganTh k 2 yang dinyatakan lulus kab.Kuningan
Th k 2 yang dinyatakan lulus kab.Kuninganbenipurnama
 

Viewers also liked (20)

News Fotoss
News FotossNews Fotoss
News Fotoss
 
Dvd digipaks examples
Dvd digipaks  examplesDvd digipaks  examples
Dvd digipaks examples
 
Energy efficiency presentation
Energy efficiency presentationEnergy efficiency presentation
Energy efficiency presentation
 
What could you do with XinSpring?
What could you do with XinSpring?What could you do with XinSpring?
What could you do with XinSpring?
 
Materisoalips
MaterisoalipsMaterisoalips
Materisoalips
 
Social Media: Am I Doing it Right?
Social Media: Am I Doing it Right?Social Media: Am I Doing it Right?
Social Media: Am I Doing it Right?
 
Begbroke transfer - making the most of your website
Begbroke transfer - making the most of your websiteBegbroke transfer - making the most of your website
Begbroke transfer - making the most of your website
 
social marketing
social marketingsocial marketing
social marketing
 
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς
Η χρήση του Web 2.0 και της κοινωνικής δικτύωσης στη Βιβλιοθήκη Λιβαδειάς
 
Redis varnish js
Redis varnish jsRedis varnish js
Redis varnish js
 
Ensamble coral como momento de arendizaje
Ensamble coral como momento de arendizajeEnsamble coral como momento de arendizaje
Ensamble coral como momento de arendizaje
 
XinSpring the system for marketing teams
XinSpring the system for marketing teamsXinSpring the system for marketing teams
XinSpring the system for marketing teams
 
Home Study Questionnaire Joint
Home Study Questionnaire JointHome Study Questionnaire Joint
Home Study Questionnaire Joint
 
Visualization of evolutionary cascades of messages using force-directed graphs
Visualization of evolutionary cascades of messages using force-directed graphsVisualization of evolutionary cascades of messages using force-directed graphs
Visualization of evolutionary cascades of messages using force-directed graphs
 
Nov 2 Class
Nov 2 ClassNov 2 Class
Nov 2 Class
 
Video analysis - Paramore
Video analysis - ParamoreVideo analysis - Paramore
Video analysis - Paramore
 
Incident Management
Incident ManagementIncident Management
Incident Management
 
Desafios matematicos
Desafios matematicosDesafios matematicos
Desafios matematicos
 
Architetti, Shamir by EF Cinisello
Architetti, Shamir by EF CiniselloArchitetti, Shamir by EF Cinisello
Architetti, Shamir by EF Cinisello
 
Th k 2 yang dinyatakan lulus kab.Kuningan
Th k 2 yang dinyatakan lulus kab.KuninganTh k 2 yang dinyatakan lulus kab.Kuningan
Th k 2 yang dinyatakan lulus kab.Kuningan
 

Similar to Bacbkone js

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011Alessandro Nadalin
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 

Similar to Bacbkone js (20)

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 

More from Артём Курапов (8)

Scaling GraphQL Subscriptions
Scaling GraphQL SubscriptionsScaling GraphQL Subscriptions
Scaling GraphQL Subscriptions
 
Variety of automated tests
Variety of automated testsVariety of automated tests
Variety of automated tests
 
Symfony
SymfonySymfony
Symfony
 
Php storm intro
Php storm introPhp storm intro
Php storm intro
 
Android intro
Android introAndroid intro
Android intro
 
В облаке AWS
В облаке AWSВ облаке AWS
В облаке AWS
 
Devclub hääletamine
Devclub hääletamineDevclub hääletamine
Devclub hääletamine
 
OAuthоризация и API социальных сетей
OAuthоризация и API социальных сетейOAuthоризация и API социальных сетей
OAuthоризация и API социальных сетей
 

Bacbkone js

  • 1. BACKBONE.JS Javascript framework intro // based on Artjom Kurapov’s experience on Weekendee project
  • 2. Problem (JS) code becomes messy Dynamic HTML (done any dynamic tables with jquery?)
  • 3. Lots of 0-level UI functions
  • 4. Solution Object Oriented code = more focus on what, less on function Higher level of abstraction = more layers
  • 5. Enter JS frameworks Hello ladies..
  • 6. Details please  View — Collection — Model ( MVC, right? )  Lightweight (6kb ≠ Extjs 1mb)  JSON, pure REST (remember PUT/DELETE http headers?)  Event driven (bang your head here)
  • 7. SO its not a  DOM manipulation lib (jquery, prototype, mootools)  Animation kit  Control suite (jquery UI, ExtJS)
  • 8. Core Concepts  Models — storage  Collections — grouping  Views — rendering  Router — navigation
  • 12. Now can be used as me.set({someAttr:’Today!’}); me.save(); … but we can handle saving too … .save({success:.., error:..}); … and tie it to some view … SomeEventView.model
  • 13. Actual model definition Weekendee.Models.Event = Backbone.Model.extend({ defaults: { }, url: function () { if (this.id === undefined) this.id = ''; return base_url + 'event/' + this.id; }, validate: function (attrs) { if (attrs.text != null && $.trim(attrs.text) == '') { return t('event.error_empty'); } } });
  • 14. Kohana controller in back public function action_index() { $requestMethod = $this->request->method(); switch ($requestMethod) { case 'GET': $eventId = $this->request->param('id'); $this->_read(); break; case 'POST': $eventId = $this->request->param('id'); if (!$eventId) { $this->_create(); } else if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $httpMethodOverride = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; if ($httpMethodOverride == "PUT") { $this->_update(); } else if ($httpMethodOverride == "DELETE") { $this->_delete(); } } break; default: $this->_read(); } }
  • 15. Views
  • 18. Views – most important  .extend  events:{}  .el  .initialize() -> .render() -> .template()
  • 20. Actual view definition Weekendee.Views.EventComment = Backbone.View.extend({ className: 'comment clearAfter’, template: _.template($('#event-comment-template').html()), events: {'click a.removeComment': 'removeComment’}, render: function () { var template_vars = this.model.toJSON(); template_vars.text = replaceURLWithHTMLLinks(template_vars.comment); $(this.el).html(this.template(template_vars)); $(this.el).attr('data-id', this.model.get('commentId')); $('h3', $(this.el)).css('color', this.model.get('color')); return this; }, removeComment: function () { this.model.destroy(); this.remove(); } });
  • 23. Actual collection definition Weekendee.Collections.FriendRequests = Backbone.Collection.extend({ page: 1, url: function () { return base_url + 'user/list_friend_requests/?page=' + this.page; }, parse: function (resp) { this.page = resp.page; this.perPage = resp.per_page; this.total = resp.total; return resp.models; } });
  • 24. Actual collection creation Weekendee.Views.ContactsPage = Backbone.View.extend({ "el": "#contacts", show: function () { this.friendRequestsView = new Weekendee.Views.FriendRequests({ collection: new Weekendee.Collections.FriendRequests() }); …
  • 25. Actual collection view Weekendee.Views.FriendRequests = Backbone.View.extend({ 'el': '#friend_requests’, initialize: function () { this.collection.bind('reset', this.reset, this); this.collection.fetch(); }, reset: function (FriendRequestWrapper) { var me = this; $('.contacts-body', $(this.el)).html(''); $.each(FriendRequestWrapper.models, function (i, model) { var view = new Weekendee.Views.FriendRequest({ model: new Weekendee.Models.Contact(model) }); $('.contacts-body', $(me.el)).append(view.render().el); }); } });
  • 28. Actual router Weekendee.Routers.AppRouter = Backbone.Router.extend({ routes: { "/week": "week", // #/week "/": "week", "": "week", "/contacts": "contacts", // #/week //"/week/:year/:week": "week",// #/week/2011/13 //"/week/:startdate": "week", // #/week/2011-10-07 "/event/:id": "event", // #/event/123 "/event/:id/:uid": "event", // external facebook links "/vibe/:id": "vibe", // #/vibe/123 "/invite/:id": "invite", // #/vibe/123 "/*": "initial” }, week: function () { Weekendee.WeekPage.reload(); Weekendee.WeekPage.show(); //Weekendee.WeekPage.setSlider(sliderState); Weekendee.ContactsPage.hide(); },
  • 30. Problems  Event propagation - loss of bind context var me = this; var comment = new Weekendee.Models.EventComment(commentModel); me.collection.add(comment); comment.bind('destroy', me.removeComment, me);  Hard to debug if you’re being dumb – model is not printable userModel.set(‘name’,’Dr. Who?’);
  • 31. Problems  Lack of documentation / best practices…
  • 32. Problems  (because of) big variety of connectivity combinations: X Models (update/get updated by) Y Views with Z Collections  And thus.. How to bind stuff correctly?  Manage collection of views?