SlideShare a Scribd company logo
1 of 24
JavaScript!
JavaScript v1
• Main features: handle browser events (load, mouse, etc.) and
  navigate and manipulate the web page document
• Primary original use was for image swapping on mouse events
  and basic form validation
• Browser rendering engines were too underpowered to do
  anything cool with it
• Inconsistent implementations between browsers
  • Netscape 3 (who made it) was a full version ahead of IE 3
JavaScript v1
• Most “serious” developers hated it
  •   No IDE
  •   No debugging tools
  •   Security flaws
  •   Marketed as “JavaScript for dummies”
  •   Mostly used by web designers
      copy-paste-ing code
Browser v4
• Netscape and IE 4 introduce completely separate
  implementations of Dynamic HTML / Document Object Model
• Libraries were created to make Netscape code work in IE and
  vice versa
• Lowest common denominator was too low to accomplish
  anything
Browser v4
• Two side effects:
  • Netscape died to give way to Mozilla, but it was years before
    Mozilla had a stable release, allowing IE to dominate market
    share
  • Flash was really the only consistent platform to do anything cool
My Favourite JavaScript Quote
“Anyway I know only one programming language worse than C
and that is JavaScript. [...] the net result is that the programming-
vacuum filled itself with the most horrible kluge in the history of
computing: JavaScript.”
 - Robert Cailliau
Enter AJAX
• Most devs more or less ignored JavaScript as a useful language
  until AJAX came along
• AJAX suddenly enabled great user experiences on web pages
  by loading data / html / scripts after the initial page load, not
  requiring a browser refresh between actions
• A number of cross-browser AJAX frameworks emerged that
  also enabled other cross-browser functionality
  • Prototype, jQuery, MooTools, Dojo, etc.
• Debugging tools created (firebug, dev console), better support
  in IDEs, browser rendering more powerful
• All in all, JavaScript is good now (or at least better)
JavaScript – Functions
• Functions are objects
  •   Have their own properties and methods (length, call, etc.)
  •   Can be assigned to variables
  •   Can be passed as arguments
  •   Can be returned by other functions
  •   Can be nested, maintaining scope (see: closure)
JavaScript – Objects
• Prototype-based Objects
  • Every object has a “prototype” property that references another
    object
  • Prototype is only used for retrieval
     • If our object doesn’t have the requested property, it’ll check its
       prototype (and its prototype, and its prototype, and so on…)
  • Prototypes are dynamic
     • editing a prototype means all of its objects are affected, regardless of
       when they were created
JavaScript – Literal Notation
•   Easy inline way to declare objects and arrays
•   aka JSON
•   Object: { Property: Value }
•   Array: [1, 2, 3]
•   Object Array: [{Property: Value}, {Property: Value}]
JavaScript – Scope
• Scope
  • Scope in JavaScript is controlled by Functions, not Blocks
  • Variables declared outside of a function / object (or without var)
    are automatically Global
      • Can lead to terrible conflicts between scripts
• Context (this)
  • “this” refers to the owner of the function being called
  • Anonymous functions are owned by Global (window)
  • Event handlers are owned by the control firing the event
    (sometimes)
JavaScript
• Bad Stuff
  •   Global Variables by default
  •   Lack of language-defined modules / namespaces
  •   No standard for distributing code across files
  •   Pretty small core library
  •   All numbers are binary floating points
       • Makes bitwise operators REALLY inefficient
  • NaN
       • typeof NaN === ‘number’ //true
       • NaN === NaN //false
  •   0, NaN, ‘’, false, null, and undefined all evaluate to false
  •   == behaves differently from ===
  •   No real way to “protect” source code / IP
  •   Still some browser-specific inconsistencies
       • *cough* Internet Explorer *cough*
jQuery
•   DOM selection using selector syntax
•   DOM traversal and modification
•   Event binding and delegation
•   CSS manipulation
•   AJAX
•   Extensibility
•   Cross-browser support
jQuery - Selectors
jQuery selectors are AWESOME.

Pre-jQuery                                              jQuery

var classElements = new Array();                        var classElements = $(“.happyCat”);
function getElementsByClassName(className, element) {
  if(element.className == className) {
     classElements.push(element);
  }
  for(var node in element.childNodes) {
     getElementsByClassName(
        className, node);
  }
}
getElementsByClassName(“sadPanda”,
  document.body);
jQuery - Selectors
                                                                    :last
   :animated
                   :visible       *alt=“backgroundImage”+
                                                                :even
    #playlistTable
                                      :checked
             :button                                        td.name + td.address

                              :contains(“Hello”)
   :parent                                             .className

                                              :gt(5)
    :first-child         table > tr




“#playlistTable td.name:odd > img*alt|=“chad”+:visible”
jQuery - Manipulation
• Allows reading, editing, insertion, deletion, and replication of
  elements and attributes in the document
   • $(‘#playlistTable’).append(“<div>Hello</div>”)
   • $(‘.userRow’).addClass(‘selected’);
   • $(‘#accountTable tr’).detach();
      • See also: $(‘#accountTable’).empty();
   • $(‘#errorMessage’).html(“<b>I didn’t say Simon Says</b>”);
   • $(‘#errorMessage’).css(‘color’, ‘red’);
   • $(‘#errorMessage’).css(‘color’); //returns ‘red’
   • $(‘input:text’).val(“I HAVE TAKEN OVER YOUR FORM”);
jQuery - Events
• Register functions to handle when the browser (or other code)
  triggers an event
  • $(‘input:button’).bind(‘click’, function() , alert(“CLICK.”); -);
  • $(‘div.hoverable’).delegate(‘mouseover’, handleHoverEvent);
  • $(document).ready(pageLoad);
jQuery - AJAX
• Make requests to the server for data / HTML / JavaScript
  without refreshing the page
  • get(“/products”, onProductsLoaded);
  • $(‘#widgetDialog’).load(“/widgets/editProduct”);
  • var formData = $(‘form’).serialize();
    post(“/saveProduct”, formdata, onProductSaved);
jQuery - Extensibility
• Hundreds of jQuery plugins
jQuery Templates
• Sends a template of how data should be represented with the
  page, then sends the data to fill that template with
Backbone.js
•   Client-side JavaScript MVC framework
•   Models with custom events
•   Collections with enumerable functions
•   Views with declarative event handling
•   Integrates with RESTful JSON web services
Backbone - Collections
• Represents a group of models
• Maps to a REST endpoint
  • /products
• Collection.fetch – calls REST endpoint, parses result, creates
  model objects, adds to collection
• Fires “refresh”, “add”, “remove”, “change” events
• Provides enumeration functions over models (foreach, find,
  map, max, min, sort, indexof, etc)
Backbone - Models
• Represents the data from the server as a property bag
  • Model.get(“property”), Model.set(,Property: “value”-)
• Provides methods to interact with REST service
  • Fetch, save, destroy
• Provides validation
• Fires events (“changed”)
Backbone - Views
• Represents the view of a model or a control on a page
  • More of a ViewModel than a true View
• Tied to a root element in the page (View.el)
• Responds to events on its model or collection
  • this.model.bind(‘change’, this.render);
• Declarative Events
   , “click .icon”: “open” -
• Use in conjunction with jQuery
  • this.$(‘.selector’) === $(‘.selector’, this.el)

More Related Content

What's hot

Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
Angel Ruiz
 

What's hot (19)

Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
Jquery
JqueryJquery
Jquery
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and Bling
 
jQuery
jQueryjQuery
jQuery
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Organizing Code with JavascriptMVC
Organizing Code with JavascriptMVCOrganizing Code with JavascriptMVC
Organizing Code with JavascriptMVC
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
 
bcgr3-jquery
bcgr3-jquerybcgr3-jquery
bcgr3-jquery
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
 

Viewers also liked (6)

What The F#
What The F#What The F#
What The F#
 
Total Engagement
Total EngagementTotal Engagement
Total Engagement
 
Node.js
Node.jsNode.js
Node.js
 
Give your web apps some backbone
Give your web apps some backboneGive your web apps some backbone
Give your web apps some backbone
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
Single page apps and the web of tomorrow
Single page apps and the web of tomorrowSingle page apps and the web of tomorrow
Single page apps and the web of tomorrow
 

Similar to JavaScript!

SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
Mark Rackley
 
J query presentation
J query presentationJ query presentation
J query presentation
akanksha17
 
J query presentation
J query presentationJ query presentation
J query presentation
sawarkar17
 

Similar to JavaScript! (20)

Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Jquery
JqueryJquery
Jquery
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
bcgr3-jquery
bcgr3-jquerybcgr3-jquery
bcgr3-jquery
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
Easy javascript
Easy javascriptEasy javascript
Easy javascript
 
Week3
Week3Week3
Week3
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
 
JS Essence
JS EssenceJS Essence
JS Essence
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
J query presentation
J query presentationJ query presentation
J query presentation
 
J query presentation
J query presentationJ query presentation
J query presentation
 
Jqueryppt (1)
Jqueryppt (1)Jqueryppt (1)
Jqueryppt (1)
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
 
J query
J queryJ query
J query
 

More from RTigger

Async in .NET
Async in .NETAsync in .NET
Async in .NET
RTigger
 

More from RTigger (14)

You Can't Buy Agile
You Can't Buy AgileYou Can't Buy Agile
You Can't Buy Agile
 
Caching up is hard to do: Improving your Web Services' Performance
Caching up is hard to do: Improving your Web Services' PerformanceCaching up is hard to do: Improving your Web Services' Performance
Caching up is hard to do: Improving your Web Services' Performance
 
Ready, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming languageReady, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming language
 
Open source web services
Open source web servicesOpen source web services
Open source web services
 
How to hire a hacker
How to hire a hackerHow to hire a hacker
How to hire a hacker
 
Windows 8 programming with html and java script
Windows 8 programming with html and java scriptWindows 8 programming with html and java script
Windows 8 programming with html and java script
 
Open regina
Open reginaOpen regina
Open regina
 
Async in .NET
Async in .NETAsync in .NET
Async in .NET
 
Hackers, hackathons, and you
Hackers, hackathons, and youHackers, hackathons, and you
Hackers, hackathons, and you
 
AJAX, JSON, and Client-Side Templates
AJAX, JSON, and Client-Side TemplatesAJAX, JSON, and Client-Side Templates
AJAX, JSON, and Client-Side Templates
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Sql vs NoSQL
Sql vs NoSQLSql vs NoSQL
Sql vs NoSQL
 
Git’in Jiggy With Git
Git’in Jiggy With GitGit’in Jiggy With Git
Git’in Jiggy With Git
 
Web Services
Web ServicesWeb Services
Web Services
 

Recently uploaded

+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)

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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+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...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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...
 
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...
 

JavaScript!

  • 2. JavaScript v1 • Main features: handle browser events (load, mouse, etc.) and navigate and manipulate the web page document • Primary original use was for image swapping on mouse events and basic form validation • Browser rendering engines were too underpowered to do anything cool with it • Inconsistent implementations between browsers • Netscape 3 (who made it) was a full version ahead of IE 3
  • 3. JavaScript v1 • Most “serious” developers hated it • No IDE • No debugging tools • Security flaws • Marketed as “JavaScript for dummies” • Mostly used by web designers copy-paste-ing code
  • 4. Browser v4 • Netscape and IE 4 introduce completely separate implementations of Dynamic HTML / Document Object Model • Libraries were created to make Netscape code work in IE and vice versa • Lowest common denominator was too low to accomplish anything
  • 5. Browser v4 • Two side effects: • Netscape died to give way to Mozilla, but it was years before Mozilla had a stable release, allowing IE to dominate market share • Flash was really the only consistent platform to do anything cool
  • 6. My Favourite JavaScript Quote “Anyway I know only one programming language worse than C and that is JavaScript. [...] the net result is that the programming- vacuum filled itself with the most horrible kluge in the history of computing: JavaScript.” - Robert Cailliau
  • 7. Enter AJAX • Most devs more or less ignored JavaScript as a useful language until AJAX came along • AJAX suddenly enabled great user experiences on web pages by loading data / html / scripts after the initial page load, not requiring a browser refresh between actions • A number of cross-browser AJAX frameworks emerged that also enabled other cross-browser functionality • Prototype, jQuery, MooTools, Dojo, etc. • Debugging tools created (firebug, dev console), better support in IDEs, browser rendering more powerful • All in all, JavaScript is good now (or at least better)
  • 8. JavaScript – Functions • Functions are objects • Have their own properties and methods (length, call, etc.) • Can be assigned to variables • Can be passed as arguments • Can be returned by other functions • Can be nested, maintaining scope (see: closure)
  • 9. JavaScript – Objects • Prototype-based Objects • Every object has a “prototype” property that references another object • Prototype is only used for retrieval • If our object doesn’t have the requested property, it’ll check its prototype (and its prototype, and its prototype, and so on…) • Prototypes are dynamic • editing a prototype means all of its objects are affected, regardless of when they were created
  • 10. JavaScript – Literal Notation • Easy inline way to declare objects and arrays • aka JSON • Object: { Property: Value } • Array: [1, 2, 3] • Object Array: [{Property: Value}, {Property: Value}]
  • 11. JavaScript – Scope • Scope • Scope in JavaScript is controlled by Functions, not Blocks • Variables declared outside of a function / object (or without var) are automatically Global • Can lead to terrible conflicts between scripts • Context (this) • “this” refers to the owner of the function being called • Anonymous functions are owned by Global (window) • Event handlers are owned by the control firing the event (sometimes)
  • 12. JavaScript • Bad Stuff • Global Variables by default • Lack of language-defined modules / namespaces • No standard for distributing code across files • Pretty small core library • All numbers are binary floating points • Makes bitwise operators REALLY inefficient • NaN • typeof NaN === ‘number’ //true • NaN === NaN //false • 0, NaN, ‘’, false, null, and undefined all evaluate to false • == behaves differently from === • No real way to “protect” source code / IP • Still some browser-specific inconsistencies • *cough* Internet Explorer *cough*
  • 13. jQuery • DOM selection using selector syntax • DOM traversal and modification • Event binding and delegation • CSS manipulation • AJAX • Extensibility • Cross-browser support
  • 14. jQuery - Selectors jQuery selectors are AWESOME. Pre-jQuery jQuery var classElements = new Array(); var classElements = $(“.happyCat”); function getElementsByClassName(className, element) { if(element.className == className) { classElements.push(element); } for(var node in element.childNodes) { getElementsByClassName( className, node); } } getElementsByClassName(“sadPanda”, document.body);
  • 15. jQuery - Selectors :last :animated :visible *alt=“backgroundImage”+ :even #playlistTable :checked :button td.name + td.address :contains(“Hello”) :parent .className :gt(5) :first-child table > tr “#playlistTable td.name:odd > img*alt|=“chad”+:visible”
  • 16. jQuery - Manipulation • Allows reading, editing, insertion, deletion, and replication of elements and attributes in the document • $(‘#playlistTable’).append(“<div>Hello</div>”) • $(‘.userRow’).addClass(‘selected’); • $(‘#accountTable tr’).detach(); • See also: $(‘#accountTable’).empty(); • $(‘#errorMessage’).html(“<b>I didn’t say Simon Says</b>”); • $(‘#errorMessage’).css(‘color’, ‘red’); • $(‘#errorMessage’).css(‘color’); //returns ‘red’ • $(‘input:text’).val(“I HAVE TAKEN OVER YOUR FORM”);
  • 17. jQuery - Events • Register functions to handle when the browser (or other code) triggers an event • $(‘input:button’).bind(‘click’, function() , alert(“CLICK.”); -); • $(‘div.hoverable’).delegate(‘mouseover’, handleHoverEvent); • $(document).ready(pageLoad);
  • 18. jQuery - AJAX • Make requests to the server for data / HTML / JavaScript without refreshing the page • get(“/products”, onProductsLoaded); • $(‘#widgetDialog’).load(“/widgets/editProduct”); • var formData = $(‘form’).serialize(); post(“/saveProduct”, formdata, onProductSaved);
  • 19. jQuery - Extensibility • Hundreds of jQuery plugins
  • 20. jQuery Templates • Sends a template of how data should be represented with the page, then sends the data to fill that template with
  • 21. Backbone.js • Client-side JavaScript MVC framework • Models with custom events • Collections with enumerable functions • Views with declarative event handling • Integrates with RESTful JSON web services
  • 22. Backbone - Collections • Represents a group of models • Maps to a REST endpoint • /products • Collection.fetch – calls REST endpoint, parses result, creates model objects, adds to collection • Fires “refresh”, “add”, “remove”, “change” events • Provides enumeration functions over models (foreach, find, map, max, min, sort, indexof, etc)
  • 23. Backbone - Models • Represents the data from the server as a property bag • Model.get(“property”), Model.set(,Property: “value”-) • Provides methods to interact with REST service • Fetch, save, destroy • Provides validation • Fires events (“changed”)
  • 24. Backbone - Views • Represents the view of a model or a control on a page • More of a ViewModel than a true View • Tied to a root element in the page (View.el) • Responds to events on its model or collection • this.model.bind(‘change’, this.render); • Declarative Events , “click .icon”: “open” - • Use in conjunction with jQuery • this.$(‘.selector’) === $(‘.selector’, this.el)