SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
Better code in
  JavaScript
nhm tanveer hossain khan (hasan)




                             tekSymmetry
How many of us write
 code in javascript?
• // global scoped function
  // no other script can’t use the
  // same name it’d be overridden
  function doSomething(p1, p2) {
     // big chunk of document.getElementById
     // messed up innerHTML = “<b>foo..
     // dirty duplicate code
  }
                                tekSymmetry
What is our
        understanding?
“God will assign javascript bugs to those who will go to
                        HELL!”




                                           tekSymmetry
Then what’s more?
• Browser compatibility sux!
• Stupid scripting language
• Hard to manage!
• Verbose
• No Object Oriented Programming!
• so anything more....?
                             tekSymmetry
Browser compatibility?
• IE6 ? Organized, Better, Understandable and
  Humanized code doesn’t hurt at all!
• “Operation canceled” (IE6)
 • Check out DOM related script
• “Undefined” use “var” while declaring
  variable
• Check null wherever possible
                                 tekSymmetry
Stupid scripting
         language?
• Not easy to debug!
• No smart IDE
• Not standard, easy to write spaghetti code
• Better! write less javascript
• Performance sux!
                                 tekSymmetry
Hard to manage!

• Do you really think that?
• How hard?
• How strong intention you have?
• How about this... (next slide)
                               tekSymmetry
Example - 1
•   var Teks = {
      FantasyFootball: {
                                             •
        Util: {                                  function debug(pMessage) {
          debug: function(pMessage) {              if (window.console != null) {

                                            VS
            if (window.console != null) {            window.console(pMessage);
              window.console(pMessage);            }
            }                                    }
          }
        }
      }
    }




                                                           tekSymmetry
Good or Bad!
  Teks.FantasyFootball.Util.
                               VS     debug(“Hello world”)
    debug(“Hello world”)


Good
- Nothing going to be messed up with other libraries
- Understandable, which “debug” function
- Easy to group similar functionalities

Bad
- Increased line of codes initially
                                            tekSymmetry
Live example!
Live example (2)!
Object Oriented
     Programming (!)
• Javascript is Object oriented programming
  platform (Real object)
• Everything is prototyping
• No class, everything is object
• Every function is prototype able
• example goes (on next slide...)
                                 tekSymmetry
Object Oriented?
•   // Constructor method
    function Logger(pName) {
      this.mType = /* other logic */;
      this.mName = pName;
                                         var log = new Logger(“Test”);
                                         log.debug(‘hello world’);
        // Member method
        debug = function(pMessage) {
          if (this.mType == ‘debug’) {
            this.log(this.mType,
                     this.mName,
                     pMessage);
          }
        }
    }

                                                       tekSymmetry
Few notes


• Use javascript as separate concerns
• Use javascript framework such as jQuery,
  Prototype



                                tekSymmetry
Separate concerns!

• Don’t embed javascript on HTML
• Keep javascript code on “application.js” (for
  rails dev)
• Apply events based on content and
  context.


                                  tekSymmetry
jQuery!
• document.getElementById(‘div_id’) VS $
  (‘#div_id’)
• ulElement.parent.getElementsByTagName
  (“li”) VS $ulElement.parent().children(“li”)
• <body onload=...> VS $(document).ready
  (function() {})
• <a click=”...”> VS $(‘#a_link’).bind(‘click’,
  function() {...}
                                     tekSymmetry
jQuery (2)!
• document.getElementById(‘form1’).submit()
  VS $(‘#form1’).trigger(‘submit’)
• new XMLHttpRequest(...) VS $.ajax({
    type: “POST”,
    url: “/url/here”,
    data: “p1=v1&p2=v2”,
    success: function(pMsg) {
    }
  })
                                     tekSymmetry
jQuery (3) - fun!
• $(“#link1”).load(“http://abc.com/url”)
• $(quot;#objectIDquot;).load(quot;/test/urlquot;, { 'params
  []': [quot;value1quot;, quot;value2quot;] } );
• $.getScript(‘http://abc.com/url’, function
  (pData, pStatus) {...})
• $.getJSON(‘/test/url’, function(pData,
  pStatus) {...})
                                   tekSymmetry
jQuery (4) - essentials!

• $(‘#div1’).css(‘display’, ‘none’)
• $(‘#div2’).toggle();
• $(‘#div3’).hide();
• $(‘#div3’).show();
                                      tekSymmetry
jQuery (5) - custom
        effect

• $(‘#div1’).animate({
    width: “70%”,
    opacity: 0.4
  }, 1500)



                         tekSymmetry
Must Have on your
         PC!!
• jQuery API doc application
 • http://api.jquery.com/
• Read at least -
 • http://www.sitepoint.com/article/
    oriented-programming-1/

                                tekSymmetry
Thanks
jQuery API doc for few examples!




                           tekSymmetry

Weitere ähnliche Inhalte

Was ist angesagt?

MyBB account hijacking
MyBB account hijackingMyBB account hijacking
MyBB account hijackingChris Illusion
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며지수 윤
 
Let’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementLet’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementMarian Rusnak
 
NodeJS The edge of Reason - Lille fp#6
NodeJS The edge of Reason - Lille fp#6NodeJS The edge of Reason - Lille fp#6
NodeJS The edge of Reason - Lille fp#6Thomas Haessle
 
OSML and OpenSocial 0.9
OSML and OpenSocial 0.9OSML and OpenSocial 0.9
OSML and OpenSocial 0.9MySpaceDevTeam
 
CoffeeScript - An Introduction
CoffeeScript - An IntroductionCoffeeScript - An Introduction
CoffeeScript - An IntroductionManvendra Singh
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptzachwise
 
Node.js et NPM: de la récupération de dépendances à la publication de paquets
Node.js et NPM: de la récupération de dépendances à la publication de paquetsNode.js et NPM: de la récupération de dépendances à la publication de paquets
Node.js et NPM: de la récupération de dépendances à la publication de paquetsFrank Rousseau
 

Was ist angesagt? (13)

MyBB account hijacking
MyBB account hijackingMyBB account hijacking
MyBB account hijacking
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며
 
Let’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementLet’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElement
 
Java script
Java scriptJava script
Java script
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
 
NodeJS The edge of Reason - Lille fp#6
NodeJS The edge of Reason - Lille fp#6NodeJS The edge of Reason - Lille fp#6
NodeJS The edge of Reason - Lille fp#6
 
OSML and OpenSocial 0.9
OSML and OpenSocial 0.9OSML and OpenSocial 0.9
OSML and OpenSocial 0.9
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
 
CoffeeScript - An Introduction
CoffeeScript - An IntroductionCoffeeScript - An Introduction
CoffeeScript - An Introduction
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Node.js et NPM: de la récupération de dépendances à la publication de paquets
Node.js et NPM: de la récupération de dépendances à la publication de paquetsNode.js et NPM: de la récupération de dépendances à la publication de paquets
Node.js et NPM: de la récupération de dépendances à la publication de paquets
 
jQuery
jQueryjQuery
jQuery
 

Ähnlich wie Better code in JavaScript

Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Developmentwolframkriesing
 
javascript teach
javascript teachjavascript teach
javascript teachguest3732fa
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_Whiteguest3732fa
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Jscript Fundamentals
Jscript FundamentalsJscript Fundamentals
Jscript Fundamentalsrspaike
 
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 librariesSimon Willison
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for JavaCharles Anderson
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil Crosby
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersYehuda Katz
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQueryAndy Gibson
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureSimon Willison
 
Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyonddion
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQueryPaul Bakaus
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuerykatbailey
 

Ähnlich wie Better code in JavaScript (20)

Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
javascript teach
javascript teachjavascript teach
javascript teach
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Jscript Fundamentals
Jscript FundamentalsJscript Fundamentals
Jscript Fundamentals
 
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
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQuery
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
 
Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyond
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQuery
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuery
 
Jslunch6
Jslunch6Jslunch6
Jslunch6
 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
 

Mehr von nhm taveer hossain khan

RubyConfBD 2013 decouple, bundle and share with ruby gems
RubyConfBD 2013   decouple, bundle and share with ruby gems RubyConfBD 2013   decouple, bundle and share with ruby gems
RubyConfBD 2013 decouple, bundle and share with ruby gems nhm taveer hossain khan
 
Agile Scrum Kanban (BASIS SoftExpo 2011)
Agile Scrum Kanban (BASIS SoftExpo 2011)Agile Scrum Kanban (BASIS SoftExpo 2011)
Agile Scrum Kanban (BASIS SoftExpo 2011)nhm taveer hossain khan
 
phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!nhm taveer hossain khan
 
Let s imagine you have contributed to build the better bangladesh
Let s imagine you have contributed to build the better bangladeshLet s imagine you have contributed to build the better bangladesh
Let s imagine you have contributed to build the better bangladeshnhm taveer hossain khan
 
Agile Project Management Basis Software Exposition 2010
Agile Project Management Basis Software Exposition 2010Agile Project Management Basis Software Exposition 2010
Agile Project Management Basis Software Exposition 2010nhm taveer hossain khan
 
Whats Preventing Me To Write Nearly Accurate Code.Key
Whats Preventing Me To Write Nearly Accurate Code.KeyWhats Preventing Me To Write Nearly Accurate Code.Key
Whats Preventing Me To Write Nearly Accurate Code.Keynhm taveer hossain khan
 

Mehr von nhm taveer hossain khan (13)

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
RubyConfBD 2013 decouple, bundle and share with ruby gems
RubyConfBD 2013   decouple, bundle and share with ruby gems RubyConfBD 2013   decouple, bundle and share with ruby gems
RubyConfBD 2013 decouple, bundle and share with ruby gems
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Agile Scrum Kanban (BASIS SoftExpo 2011)
Agile Scrum Kanban (BASIS SoftExpo 2011)Agile Scrum Kanban (BASIS SoftExpo 2011)
Agile Scrum Kanban (BASIS SoftExpo 2011)
 
phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!
 
Hi code man! ain't you crazy enough ?
Hi code man! ain't you crazy enough ?Hi code man! ain't you crazy enough ?
Hi code man! ain't you crazy enough ?
 
Let s imagine you have contributed to build the better bangladesh
Let s imagine you have contributed to build the better bangladeshLet s imagine you have contributed to build the better bangladesh
Let s imagine you have contributed to build the better bangladesh
 
Ain't you crazy enough ?
Ain't you crazy enough ?Ain't you crazy enough ?
Ain't you crazy enough ?
 
Agile Project Management Basis Software Exposition 2010
Agile Project Management Basis Software Exposition 2010Agile Project Management Basis Software Exposition 2010
Agile Project Management Basis Software Exposition 2010
 
Ruby on Rails small application demo
Ruby on Rails small application demoRuby on Rails small application demo
Ruby on Rails small application demo
 
Developing Quality Web Application
Developing Quality Web ApplicationDeveloping Quality Web Application
Developing Quality Web Application
 
TekS Short Git Overview
TekS Short Git OverviewTekS Short Git Overview
TekS Short Git Overview
 
Whats Preventing Me To Write Nearly Accurate Code.Key
Whats Preventing Me To Write Nearly Accurate Code.KeyWhats Preventing Me To Write Nearly Accurate Code.Key
Whats Preventing Me To Write Nearly Accurate Code.Key
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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 WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+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...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Better code in JavaScript

  • 1. Better code in JavaScript nhm tanveer hossain khan (hasan) tekSymmetry
  • 2. How many of us write code in javascript? • // global scoped function // no other script can’t use the // same name it’d be overridden function doSomething(p1, p2) { // big chunk of document.getElementById // messed up innerHTML = “<b>foo.. // dirty duplicate code } tekSymmetry
  • 3. What is our understanding? “God will assign javascript bugs to those who will go to HELL!” tekSymmetry
  • 4. Then what’s more? • Browser compatibility sux! • Stupid scripting language • Hard to manage! • Verbose • No Object Oriented Programming! • so anything more....? tekSymmetry
  • 5. Browser compatibility? • IE6 ? Organized, Better, Understandable and Humanized code doesn’t hurt at all! • “Operation canceled” (IE6) • Check out DOM related script • “Undefined” use “var” while declaring variable • Check null wherever possible tekSymmetry
  • 6. Stupid scripting language? • Not easy to debug! • No smart IDE • Not standard, easy to write spaghetti code • Better! write less javascript • Performance sux! tekSymmetry
  • 7. Hard to manage! • Do you really think that? • How hard? • How strong intention you have? • How about this... (next slide) tekSymmetry
  • 8. Example - 1 • var Teks = { FantasyFootball: { • Util: { function debug(pMessage) { debug: function(pMessage) { if (window.console != null) { VS if (window.console != null) { window.console(pMessage); window.console(pMessage); } } } } } } } tekSymmetry
  • 9. Good or Bad! Teks.FantasyFootball.Util. VS debug(“Hello world”) debug(“Hello world”) Good - Nothing going to be messed up with other libraries - Understandable, which “debug” function - Easy to group similar functionalities Bad - Increased line of codes initially tekSymmetry
  • 12. Object Oriented Programming (!) • Javascript is Object oriented programming platform (Real object) • Everything is prototyping • No class, everything is object • Every function is prototype able • example goes (on next slide...) tekSymmetry
  • 13. Object Oriented? • // Constructor method function Logger(pName) { this.mType = /* other logic */; this.mName = pName; var log = new Logger(“Test”); log.debug(‘hello world’); // Member method debug = function(pMessage) { if (this.mType == ‘debug’) { this.log(this.mType, this.mName, pMessage); } } } tekSymmetry
  • 14. Few notes • Use javascript as separate concerns • Use javascript framework such as jQuery, Prototype tekSymmetry
  • 15. Separate concerns! • Don’t embed javascript on HTML • Keep javascript code on “application.js” (for rails dev) • Apply events based on content and context. tekSymmetry
  • 16. jQuery! • document.getElementById(‘div_id’) VS $ (‘#div_id’) • ulElement.parent.getElementsByTagName (“li”) VS $ulElement.parent().children(“li”) • <body onload=...> VS $(document).ready (function() {}) • <a click=”...”> VS $(‘#a_link’).bind(‘click’, function() {...} tekSymmetry
  • 17. jQuery (2)! • document.getElementById(‘form1’).submit() VS $(‘#form1’).trigger(‘submit’) • new XMLHttpRequest(...) VS $.ajax({ type: “POST”, url: “/url/here”, data: “p1=v1&p2=v2”, success: function(pMsg) { } }) tekSymmetry
  • 18. jQuery (3) - fun! • $(“#link1”).load(“http://abc.com/url”) • $(quot;#objectIDquot;).load(quot;/test/urlquot;, { 'params []': [quot;value1quot;, quot;value2quot;] } ); • $.getScript(‘http://abc.com/url’, function (pData, pStatus) {...}) • $.getJSON(‘/test/url’, function(pData, pStatus) {...}) tekSymmetry
  • 19. jQuery (4) - essentials! • $(‘#div1’).css(‘display’, ‘none’) • $(‘#div2’).toggle(); • $(‘#div3’).hide(); • $(‘#div3’).show(); tekSymmetry
  • 20. jQuery (5) - custom effect • $(‘#div1’).animate({ width: “70%”, opacity: 0.4 }, 1500) tekSymmetry
  • 21. Must Have on your PC!! • jQuery API doc application • http://api.jquery.com/ • Read at least - • http://www.sitepoint.com/article/ oriented-programming-1/ tekSymmetry
  • 22. Thanks jQuery API doc for few examples! tekSymmetry