SlideShare una empresa de Scribd logo
1 de 23
object laterals
                               object literals
                               using objects
                                to organize
                                 your code
                                    jQuery Conference 2009 ~ Boston, MA

                                 @rmurphey ~ rebecca@rebeccamurphey.com

                             http://blog.rebeccamurphey.com/organize-your-jquery/




Sunday, September 13, 2009
me
                   •         Independent front-end architecture
                             consultant in Durham, N.C.
                   •         @rmurphey on Twitter
                   •         http://www.rebeccamurphey.com




Sunday, September 13, 2009
why objects?



Sunday, September 13, 2009
jQuery is easy to write




Sunday, September 13, 2009
complex jQuery is easy to write badly




Sunday, September 13, 2009
a simple example
                      Load some content when a list item is clicked;
                          hide the content for sibling list items




Sunday, September 13, 2009
Sunday, September 13, 2009
the url needs to be configurable
          can we cache the content?
   what about back button support?
                        animation is so web 2.0
            let’s add a lightbox!
                             doh, we forgot to mark the
                                  current list item
Sunday, September 13, 2009
// NAVIGATION
              function togglePage(section) {
                       // if the clicked section is already the current section AND we're in full page mode
                       // minimize the current tab
                       if (jQuery('#md_tab_'+ section).hasClass('current') && jQuery('#md_tab_'+ section + '
              a').hasClass('md_fullpage')) {
                            // alert('clicked section is current section AND fullpage mode is active; teaser
              should load');
                       // Minimize
                            jQuery('#md_tabs_navigation a').removeClass('md_fullpage');
                            jQuery('.md_body').hide();
                            jQuery('#md_feature').slideDown('normal',function(){
                                 var bodyContent = jQuery('#md_body_'+ section);
                                 bodyContent.fadeOut('normal',function(){
                                      jQuery('#md_tabs_navigation a').each(function(){
                                           var thisSection =
              jQuery(this).html().replace('<span<','').replace('</span<','');
                                           var thisSection_comp = thisSection.toLowerCase().replace('
              ','_');
                                           jQuery('#md_body_'+ thisSection_comp).load(
                                                '/app/modules/info/loadTeaser.php?sect='+ thisSection_comp,
                                                function(){
                                                     tb_init('.md_body a.thickbox, .md_body
              area.thickbox, .md_body input.thickbox');
                                                     bodyContent.animate({ height: 'toggle', opacity:
              'toggle' },"slow");
                                                }
                                           );
                                      });
                                 });
                            });
                            jQuery('#expandtabs span').empty().append('Expand Tabs');
                       } else {
                       // if the clicked section is NOT the current section OR we're NOT in full page mode
                       // then let's go to full page mode and show the whole tab
                       // Maximize
                            // alert('clicked section is not the current section OR full page mode is not
              active; full section should load');
                            jQuery('#md_tabs_navigation li').removeClass('current');
                            jQuery('#md_tab_'+ section).addClass('current');
                            jQuery('#md_tabs_navigation a').addClass('md_fullpage');
                            jQuery('.md_body').hide();
                            jQuery('#md_feature').slideUp('normal',function(){
                                 var bodyContent = jQuery('#md_body_'+ section);
Sunday, September 13, 2009
                                 bodyContent.fadeOut('normal',function(){
omg wtf.
                               SRRY MS
Sunday, September 13, 2009
a solution:
                                          objects
                   •         Keep the global namespace clean
                   •         Encapsulate separate behaviors in methods
                   •         Set configuration options outside methods
                   •         Self-document with good method names
                             and small methods
                   •         Make methods available to other code
Sunday, September 13, 2009
when does it make
                   sense to use objects?

                   •         About an hour after you start trying to
                             write a complex feature without them.




Sunday, September 13, 2009
no really
                   •         Features with ...
                         •     Multiple states
                         •     Multiple behaviors
                         •     Multiple points of interaction




Sunday, September 13, 2009
patterns



Sunday, September 13, 2009
object literal
                                   (singleton)
                   •         Simple setup
                   •         One instance per page
                   •         All methods and properties are public
                   •         May require initialization method




Sunday, September 13, 2009
Where are my privates!?!?
Sunday, September 13, 2009
module
                   •         Function returns an object
                   •         Self-initializing
                   •         Allows for private methods and
                             properties




Sunday, September 13, 2009
Closures ftw
Sunday, September 13, 2009
IN UR JQUERY
                             RITIN’ SOME OBJEX


Sunday, September 13, 2009
tips
                              plz?




Sunday, September 13, 2009
•       Write stubs to sketch out your feature
       •       Centralize configuration – minimize quoted
               strings in non-config code
       •       Create methods for event handling
       •       Allow for external configuration if it makes sense

Sunday, September 13, 2009
awesome stuff we
                         don’t have time for
                   •         Objects for managing code execution
                   •         Using object literals to define plugin
                             submethods
                   •         Changing the meaning of “this” inside
                             event handlers and opening up a world
                             of win (native in 1.3.3?)
                   •         You should have been at Paul Irish’s talk

Sunday, September 13, 2009
thanks.
                   •         http://blog.rebeccamurphey.com/
                             organize-your-jquery/
                   •         Rate this talk: http://speakerrate.com/
                             talks/1423
                   •         Thanks to Paul Irish, Chris Williams, Victor Hong,
                             Brian Mitchell, Ben Alman, and the folks in #jquery-ot




Sunday, September 13, 2009

Más contenido relacionado

La actualidad más candente

3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 

La actualidad más candente (20)

Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo Mixins
 
Difference BW Frontend and Backend Development
Difference BW Frontend and Backend DevelopmentDifference BW Frontend and Backend Development
Difference BW Frontend and Backend Development
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Angular 14.pptx
Angular 14.pptxAngular 14.pptx
Angular 14.pptx
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Jetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidJetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no Android
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
 
HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!
 
Front End Best Practices
Front End Best PracticesFront End Best Practices
Front End Best Practices
 
Responsive web design
Responsive web designResponsive web design
Responsive web design
 
Jquery
JqueryJquery
Jquery
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Frontend developer Roadmap .pdf
Frontend developer Roadmap .pdfFrontend developer Roadmap .pdf
Frontend developer Roadmap .pdf
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Flexbox
FlexboxFlexbox
Flexbox
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 

Destacado

jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
How Emacs changed my life
How Emacs changed my lifeHow Emacs changed my life
How Emacs changed my life
yukihiro_matz
 

Destacado (20)

How to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationHow to write a well-behaved Python command line application
How to write a well-behaved Python command line application
 
Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
 
EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysis
 
Organizing JavaScript
Organizing JavaScriptOrganizing JavaScript
Organizing JavaScript
 
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
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole Tange
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
How Emacs changed my life
How Emacs changed my lifeHow Emacs changed my life
How Emacs changed my life
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Pets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud StoryPets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud Story
 
OMA Lightweight M2M Tutorial
OMA Lightweight M2M TutorialOMA Lightweight M2M Tutorial
OMA Lightweight M2M Tutorial
 
Getting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry PiGetting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry Pi
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCRESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
 
Why Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your ShellWhy Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your Shell
 

Similar a Using Objects to Organize your jQuery Code

Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
Timothy Oxley
 

Similar a Using Objects to Organize your jQuery Code (20)

DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
 
Debugging War Stories & Strategies to Survive on RejectJS 2014
Debugging War Stories & Strategies to Survive on RejectJS 2014Debugging War Stories & Strategies to Survive on RejectJS 2014
Debugging War Stories & Strategies to Survive on RejectJS 2014
 
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesJazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
 
Workflow para desenvolvimento Web & Mobile usando grunt.js
Workflow para desenvolvimento Web & Mobile usando grunt.jsWorkflow para desenvolvimento Web & Mobile usando grunt.js
Workflow para desenvolvimento Web & Mobile usando grunt.js
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
UX Design for Developers
UX Design for DevelopersUX Design for Developers
UX Design for Developers
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
REACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScriptREACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScript
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
JavaScript: DOM and jQuery
JavaScript: DOM and jQueryJavaScript: DOM and jQuery
JavaScript: DOM and jQuery
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 

Más de Rebecca Murphey

Getting Started with Mulberry
Getting Started with MulberryGetting Started with Mulberry
Getting Started with Mulberry
Rebecca Murphey
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
Lessons from-a-rewrite-gotham
Lessons from-a-rewrite-gothamLessons from-a-rewrite-gotham
Lessons from-a-rewrite-gotham
Rebecca Murphey
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
Rebecca Murphey
 

Más de Rebecca Murphey (15)

A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
BVJS
BVJSBVJS
BVJS
 
Getting Started with Mulberry
Getting Started with MulberryGetting Started with Mulberry
Getting Started with Mulberry
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
Introducing Mulberry
Introducing MulberryIntroducing Mulberry
Introducing Mulberry
 
DojoConf: Building Large Apps
DojoConf: Building Large AppsDojoConf: Building Large Apps
DojoConf: Building Large Apps
 
Lessons from-a-rewrite-gotham
Lessons from-a-rewrite-gothamLessons from-a-rewrite-gotham
Lessons from-a-rewrite-gotham
 
Lessons from a Rewrite
Lessons from a RewriteLessons from a Rewrite
Lessons from a Rewrite
 
Modern JavaScript
Modern JavaScriptModern JavaScript
Modern JavaScript
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQuery
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
The jQuery Divide
The jQuery DivideThe jQuery Divide
The jQuery Divide
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
 

Último

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
 
+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@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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
 

Último (20)

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
 
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
 
+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...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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, ...
 

Using Objects to Organize your jQuery Code

  • 1. object laterals object literals using objects to organize your code jQuery Conference 2009 ~ Boston, MA @rmurphey ~ rebecca@rebeccamurphey.com http://blog.rebeccamurphey.com/organize-your-jquery/ Sunday, September 13, 2009
  • 2. me • Independent front-end architecture consultant in Durham, N.C. • @rmurphey on Twitter • http://www.rebeccamurphey.com Sunday, September 13, 2009
  • 4. jQuery is easy to write Sunday, September 13, 2009
  • 5. complex jQuery is easy to write badly Sunday, September 13, 2009
  • 6. a simple example Load some content when a list item is clicked; hide the content for sibling list items Sunday, September 13, 2009
  • 8. the url needs to be configurable can we cache the content? what about back button support? animation is so web 2.0 let’s add a lightbox! doh, we forgot to mark the current list item Sunday, September 13, 2009
  • 9. // NAVIGATION function togglePage(section) { // if the clicked section is already the current section AND we're in full page mode // minimize the current tab if (jQuery('#md_tab_'+ section).hasClass('current') && jQuery('#md_tab_'+ section + ' a').hasClass('md_fullpage')) { // alert('clicked section is current section AND fullpage mode is active; teaser should load'); // Minimize jQuery('#md_tabs_navigation a').removeClass('md_fullpage'); jQuery('.md_body').hide(); jQuery('#md_feature').slideDown('normal',function(){ var bodyContent = jQuery('#md_body_'+ section); bodyContent.fadeOut('normal',function(){ jQuery('#md_tabs_navigation a').each(function(){ var thisSection = jQuery(this).html().replace('<span<','').replace('</span<',''); var thisSection_comp = thisSection.toLowerCase().replace(' ','_'); jQuery('#md_body_'+ thisSection_comp).load( '/app/modules/info/loadTeaser.php?sect='+ thisSection_comp, function(){ tb_init('.md_body a.thickbox, .md_body area.thickbox, .md_body input.thickbox'); bodyContent.animate({ height: 'toggle', opacity: 'toggle' },"slow"); } ); }); }); }); jQuery('#expandtabs span').empty().append('Expand Tabs'); } else { // if the clicked section is NOT the current section OR we're NOT in full page mode // then let's go to full page mode and show the whole tab // Maximize // alert('clicked section is not the current section OR full page mode is not active; full section should load'); jQuery('#md_tabs_navigation li').removeClass('current'); jQuery('#md_tab_'+ section).addClass('current'); jQuery('#md_tabs_navigation a').addClass('md_fullpage'); jQuery('.md_body').hide(); jQuery('#md_feature').slideUp('normal',function(){ var bodyContent = jQuery('#md_body_'+ section); Sunday, September 13, 2009 bodyContent.fadeOut('normal',function(){
  • 10. omg wtf. SRRY MS Sunday, September 13, 2009
  • 11. a solution: objects • Keep the global namespace clean • Encapsulate separate behaviors in methods • Set configuration options outside methods • Self-document with good method names and small methods • Make methods available to other code Sunday, September 13, 2009
  • 12. when does it make sense to use objects? • About an hour after you start trying to write a complex feature without them. Sunday, September 13, 2009
  • 13. no really • Features with ... • Multiple states • Multiple behaviors • Multiple points of interaction Sunday, September 13, 2009
  • 15. object literal (singleton) • Simple setup • One instance per page • All methods and properties are public • May require initialization method Sunday, September 13, 2009
  • 16. Where are my privates!?!? Sunday, September 13, 2009
  • 17. module • Function returns an object • Self-initializing • Allows for private methods and properties Sunday, September 13, 2009
  • 19. IN UR JQUERY RITIN’ SOME OBJEX Sunday, September 13, 2009
  • 20. tips plz? Sunday, September 13, 2009
  • 21. Write stubs to sketch out your feature • Centralize configuration – minimize quoted strings in non-config code • Create methods for event handling • Allow for external configuration if it makes sense Sunday, September 13, 2009
  • 22. awesome stuff we don’t have time for • Objects for managing code execution • Using object literals to define plugin submethods • Changing the meaning of “this” inside event handlers and opening up a world of win (native in 1.3.3?) • You should have been at Paul Irish’s talk Sunday, September 13, 2009
  • 23. thanks. • http://blog.rebeccamurphey.com/ organize-your-jquery/ • Rate this talk: http://speakerrate.com/ talks/1423 • Thanks to Paul Irish, Chris Williams, Victor Hong, Brian Mitchell, Ben Alman, and the folks in #jquery-ot Sunday, September 13, 2009

Notas del editor

  1. jQuery gives developers a lot of freedom when it comes to structuring code; no hard-and-fast rules about right/wrong