SlideShare a Scribd company logo
Advancing JavaScript
  with Libraries
                John Resig
  ejohn.org / jquery.com / mozilla.com
Two Hats
•   Mozilla Corp               •   jQuery JavaScript
                                   Library
•   FUEL
                               •   Released Jan 2006
    •   JS Lib for Ext. Devs
                               •   Small Filesize
    •   Reduce Complexity
                               •   Short, concise, code
•   JS Lib Test Suites
                               •   Extensible via plugins
    •   Integration, better
        coverage
Libraries are...


• ...abstractions away from existing APIs
• ...giving us new APIs to interface with
Hypothesis

• APIs breed patterns
• Libraries build new patterns on top of
  existing APIs
• New library patterns advance development
  in meaningful, considerable, ways
Why Create A Library?

• Distance ourselves from repetition
• In JavaScript:
 • Distance from browser differences
• In C (stdlib):
 • Distance from platform differences
DOM API

• Implemented in every modern browser
• Most stable of all the JavaScript APIs
• Very well documented
Fails in IE 7
JavaScript:
document.getElementById(“obj”)
  .getElementsByTagName(“*”)




HTML:
<object id=”obj”>
  <param name="src" value="test.mov"/>
  <param name="title" value="My Video"/>
</object>
Fails in Safari 2
JavaScript:
document.getElementById(“opt”).selected




HTML:
<div style=”display: none;”>
  <select><option id=”opt” value=”test”/></select>
</div>
Genuine Bugs
Fails in Opera & IE
JavaScript:
document.getElementById(“q”)




HTML:
<form action="" method="POST">
  <input type="text" name="q"/>
  <span id="q">Search</span>
</form>
Fails in Opera & IE
JavaScript:
var f = document.getElementsByTagName(“input”);
for ( var i = 0; i < f.length; i++ ) { ... }




HTML:
<form action="" method="POST">
  Num Rows: <input type="text" id="length" value="22"/><br/>
  <input type="submit" value="Generate"/>
</form>
Re-interpretation
   of the Spec
Fails in All
JavaScript:
document.getElementById(“name”)
  .setAttribute(“disabled”, false);




HTML:
<input type=”text” id=”name” disabled=”disabled”/>
Fails in All
JavaScript:
document.body.setAttribute(“class”, “home”);




HTML:
<body> ... </body>
What you expect
Why are Libraries
       Created?
• Browsers have a large number of strange
  differences...
  • IE has a lot of well documented bugs
  • Safari has less, but more obscure, bugs
• APIs don’t do what you expect
• When the API is impossible to learn, but
  through experience
Break down into
      Meta-Problems

• Waiting for the document to load
• Traversing the DOM
• Injecting HTML into a page
Waiting for the DOM
       to load

• A DOM document must be fully loaded
  before you can work with it
• Waiting for the window to load causes
  flashes of un-effected content
Focusing an input
<input type=”text” id=”test”/>
<script>document.getElementById(“test”).focus();</script>




<head><script src=”script.js”</head>

$(document).ready(function(){
  $(“#test”).focus();
});
Traversing the DOM

• getElementsByTagName, getElementById,
  getAttribute, nextSibling, previousSibling,
  parentNode, className, etc.
• A lot to learn and get right
• Has the potential to be very tricky (and
  long-winded)
DOM Selectors

• Goal: Improve the DOM Traversal API
• Provide an API on top of the existing DOM
  API
• Look to standards for inspiration
Types of Selectors
• XPath Selectors
 • //div/span[2]
 • /html[@id=’home’]
• CSS 3 Selectors
 • div > span:nth-of-type(2)
 • html:root#home
Non-trivial Selectors

$(“#menu > li:not(:first-child)”).hide();

$(“ul[ul]”).show();

$(“tr:even”).addClass(“even”);
Injecting HTML

• Very frustrating problem
• Browsers are very tempermental
• (Inserting table rows, select options, etc.)
HTML Solution

• Allow users to insert HTML strings
• Convert to DOM nodes on the fly
• Inject into the document correctly
$(“table tr”).append(“<td>test</td>”);
$(“select”).prepend(“<option>test</option>”);
• DOM Ready + Selectors + HTML Injection
• The dream of true unobtrusive DOM
   scripting

$(document).ready(function(){
    $(“select”).append(“<option>None</option>”);
});
New Expectations
• What new expectations emerge out of this
  new API?

 $(“ul > li”).click(function(){
   $(this).load(“menu.html”);
 });



 <ul>
   <li>item a</li>
   <li>item b</li>
 </ul>
The Perception

• When the document was ready:
 • We bound an event to a set of elements
• We loaded some new elements
 • Why don’t they have the event?
New Pattern: Behaviors
function handleClick() {
  $(“li”, this).click(loadMenu);
}

function loadMenu() {
  $(this).load(“menu.html”, handleClick);
}

$(document).ready(function(){
  $(document).each(handleClick);
});
Behaviors

$(document).ready(function(){
  $(“li”).behavior(“click”,function(){
    $(this).load(“menu.html”);
  });
});
Pure DOM
        function handleClick( elem ) {
           var li = elem.getElementsByTagName(“li”);
           for ( var i = 0; i < li.length; i++ )
               li[i].addEventListener( “click”, loadMenu, false );
Doesn’t exist in IE
        }

      function loadMenu() {         IE sets the wrong context
          var elem = this;
  Doesn’t exist in IE = new XMLHttpRequest();
          var xhr
          xhr.open( “GET”, “menu.html”, false );
          xhr.onreadystatechange = function(){                  Leaks in IE
             if ( xhr.readyState == 4 ) {
                 elem.innerHTML = xhr.responseText;
                 handleClick( elem );
             }
          };
          xhr.send( null );
      }

       window.onload = function(){      Doesn’t happen immediately
          var ul = document.getElementsByTagName(“ul”);
          for ( var i = 0; i < ul.length; i++ )
            handleClick( ul[i] );
       };
FUEL

• JavaScript Library for Firefox Extension
  Development
• Designed to be used by Web Developers
• Current API is very C++ centric
Mozilla: Preferences
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  .getService(Components.interfaces.nsIPrefBranch);

var str = Components.classes["@mozilla.org/supports-string;1"]
  .createInstance(Components.interfaces.nsISupportsString);
str.data = "some non-ascii text";
prefs.setComplexValue("preference.with.non.ascii.value",
      Components.interfaces.nsISupportsString, str);
Preferences w/ FUEL

Application.prefs.setValue(“some.pref”, “some non-ascii text”);
SELECT * FROM users WHERE id = 5;

        SQL




                       $res = mysql_query(“SELECT * FROM users WHERE id = 5;”);
Programming Language   while ( $row = mysql_fetch_assoc($res) ) {
                         // etc.
      Interface        }




                       User.find(5)
     Abstraction
    Layer (ORM)
class Account < ActiveRecord::Base
    has_many :people do
      def find_or_create_by_name(name)
        first_name, last_name = name.split(" ", 2)
        find_or_create_by_first_name_and_last_name
(first_name, last_name)
      end
    end
  end

  person = Account.find(:first).people
    .find_or_create_by_name("David Heinemeier Hansson")
  person.first_name # => "David"
  person.last_name # => "Heinemeier Hansson"
Conclusion

• Libraries build new patterns on top of
  existing APIs
• New library patterns advance development
  in meaningful, considerable, ways
Bonus: Meta-Libraries

• Domain Specific Languages (DSLs)
• Build upon existing libraries building new
  languages out of their APIs
• “jQuery2” meta language:
  http://ejohn.org/apps/jquery2/
More info...
• http://ejohn.org/
• http://jquery.com/
• http://wiki.mozilla.org/FUEL
• http://ejohn.org/apps/jquery2/

• Contact:
  jeresig@gmail.com

More Related Content

What's hot (20)

PDF
Working with the django admin
flywindy
 
PDF
Modern, Scalable, Ambitious apps with Ember.js
Mike North
 
PPT
Javascript and Jquery Best practices
Sultan Khan
 
KEY
MongoDB at ZPUGDC
Mike Dirolf
 
KEY
The Inclusive Web: hands-on with HTML5 and jQuery
colinbdclark
 
PPTX
Jquery fundamentals
Salvatore Fazio
 
PDF
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
scalaconfjp
 
PPTX
SharePoint and jQuery Essentials
Mark Rackley
 
PDF
Django Heresies
Simon Willison
 
PDF
Elasticsearch for SQL Users
All Things Open
 
PDF
Performance Optimization and JavaScript Best Practices
Doris Chen
 
PPTX
End-to-end testing with geb
Jesús L. Domínguez Muriel
 
PPTX
Javascript for the c# developer
Salvatore Fazio
 
PDF
MongoDB & NoSQL 101
Jollen Chen
 
PPTX
Testing Ext JS and Sencha Touch
Mats Bryntse
 
PPT
JavaScript Misunderstood
Bhavya Siddappa
 
PDF
JavaScript Library Overview
jeresig
 
PDF
How to make Ajax Libraries work for you
Simon Willison
 
PPT
Coding with style: The Scalastyle style checker
Matthew Farwell
 
PPTX
Scaladays 2014 introduction to scalatest selenium dsl
Matthew Farwell
 
Working with the django admin
flywindy
 
Modern, Scalable, Ambitious apps with Ember.js
Mike North
 
Javascript and Jquery Best practices
Sultan Khan
 
MongoDB at ZPUGDC
Mike Dirolf
 
The Inclusive Web: hands-on with HTML5 and jQuery
colinbdclark
 
Jquery fundamentals
Salvatore Fazio
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
scalaconfjp
 
SharePoint and jQuery Essentials
Mark Rackley
 
Django Heresies
Simon Willison
 
Elasticsearch for SQL Users
All Things Open
 
Performance Optimization and JavaScript Best Practices
Doris Chen
 
End-to-end testing with geb
Jesús L. Domínguez Muriel
 
Javascript for the c# developer
Salvatore Fazio
 
MongoDB & NoSQL 101
Jollen Chen
 
Testing Ext JS and Sencha Touch
Mats Bryntse
 
JavaScript Misunderstood
Bhavya Siddappa
 
JavaScript Library Overview
jeresig
 
How to make Ajax Libraries work for you
Simon Willison
 
Coding with style: The Scalastyle style checker
Matthew Farwell
 
Scaladays 2014 introduction to scalatest selenium dsl
Matthew Farwell
 

Viewers also liked (6)

PDF
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
PPTX
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
PDF
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
PDF
Scalable JavaScript Application Architecture
Nicholas Zakas
 
PDF
Javascript Best Practices
Christian Heilmann
 
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Javascript Best Practices
Christian Heilmann
 
Ad

Similar to Advancing JavaScript with Libraries (Yahoo Tech Talk) (20)

PDF
Building a JavaScript Library
jeresig
 
PPTX
CT presentatie JQuery 7.12.11
virtualsciences41
 
PDF
Kann JavaScript elegant sein?
jbandi
 
PDF
New Features Coming in Browsers (RIT '09)
jeresig
 
PDF
fuser interface-development-using-jquery
Kostas Mavridis
 
PPTX
Advanced JavaScript
Mahmoud Tolba
 
PPT
Java script
vishal choudhary
 
PDF
GQuery a jQuery clone for Gwt, RivieraDev 2011
Manuel Carrasco Moñino
 
PDF
Zepto and the rise of the JavaScript Micro-Frameworks
Thomas Fuchs
 
PDF
Performance Improvements In Browsers
GoogleTecTalks
 
PDF
Performance Improvements in Browsers
jeresig
 
PDF
How to make Ajax work for you
Simon Willison
 
PDF
Ajax tutorial
Kat Roque
 
PDF
JavaScript Libraries (Ajax Exp 2006)
jeresig
 
PPTX
JS Essence
Uladzimir Piatryka
 
PDF
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
PDF
Ajax Tutorial
oscon2007
 
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
PDF
jQuery Recommendations to the W3C (2011)
jeresig
 
PDF
jQuery and the W3C
jeresig
 
Building a JavaScript Library
jeresig
 
CT presentatie JQuery 7.12.11
virtualsciences41
 
Kann JavaScript elegant sein?
jbandi
 
New Features Coming in Browsers (RIT '09)
jeresig
 
fuser interface-development-using-jquery
Kostas Mavridis
 
Advanced JavaScript
Mahmoud Tolba
 
Java script
vishal choudhary
 
GQuery a jQuery clone for Gwt, RivieraDev 2011
Manuel Carrasco Moñino
 
Zepto and the rise of the JavaScript Micro-Frameworks
Thomas Fuchs
 
Performance Improvements In Browsers
GoogleTecTalks
 
Performance Improvements in Browsers
jeresig
 
How to make Ajax work for you
Simon Willison
 
Ajax tutorial
Kat Roque
 
JavaScript Libraries (Ajax Exp 2006)
jeresig
 
JS Essence
Uladzimir Piatryka
 
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
Ajax Tutorial
oscon2007
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
jQuery Recommendations to the W3C (2011)
jeresig
 
jQuery and the W3C
jeresig
 
Ad

More from jeresig (20)

PDF
Does Coding Every Day Matter?
jeresig
 
PDF
Accidentally Becoming a Digital Librarian
jeresig
 
PDF
2014: John's Favorite Thing (Neo4j)
jeresig
 
PDF
Computer Vision as Art Historical Investigation
jeresig
 
PDF
Hacking Art History
jeresig
 
PDF
Using JS to teach JS at Khan Academy
jeresig
 
PDF
Applying Computer Vision to Art History
jeresig
 
PDF
NYARC 2014: Frick/Zeri Results
jeresig
 
PDF
EmpireJS: Hacking Art with Node js and Image Analysis
jeresig
 
PDF
Applying Computer Vision to Art History
jeresig
 
PDF
Introduction to jQuery (Ajax Exp 2006)
jeresig
 
PDF
jQuery Open Source Process (RIT 2011)
jeresig
 
PDF
jQuery Open Source Process (Knight Foundation 2011)
jeresig
 
PDF
jQuery Mobile
jeresig
 
PDF
jQuery Open Source (Fronteer 2011)
jeresig
 
PDF
Holistic JavaScript Performance
jeresig
 
PDF
Introduction to jQuery (Ajax Exp 2007)
jeresig
 
PDF
Advanced jQuery (Ajax Exp 2007)
jeresig
 
PDF
JavaScript Library Overview (Ajax Exp West 2007)
jeresig
 
PDF
Meta Programming with JavaScript
jeresig
 
Does Coding Every Day Matter?
jeresig
 
Accidentally Becoming a Digital Librarian
jeresig
 
2014: John's Favorite Thing (Neo4j)
jeresig
 
Computer Vision as Art Historical Investigation
jeresig
 
Hacking Art History
jeresig
 
Using JS to teach JS at Khan Academy
jeresig
 
Applying Computer Vision to Art History
jeresig
 
NYARC 2014: Frick/Zeri Results
jeresig
 
EmpireJS: Hacking Art with Node js and Image Analysis
jeresig
 
Applying Computer Vision to Art History
jeresig
 
Introduction to jQuery (Ajax Exp 2006)
jeresig
 
jQuery Open Source Process (RIT 2011)
jeresig
 
jQuery Open Source Process (Knight Foundation 2011)
jeresig
 
jQuery Mobile
jeresig
 
jQuery Open Source (Fronteer 2011)
jeresig
 
Holistic JavaScript Performance
jeresig
 
Introduction to jQuery (Ajax Exp 2007)
jeresig
 
Advanced jQuery (Ajax Exp 2007)
jeresig
 
JavaScript Library Overview (Ajax Exp West 2007)
jeresig
 
Meta Programming with JavaScript
jeresig
 

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 

Advancing JavaScript with Libraries (Yahoo Tech Talk)

  • 1. Advancing JavaScript with Libraries John Resig ejohn.org / jquery.com / mozilla.com
  • 2. Two Hats • Mozilla Corp • jQuery JavaScript Library • FUEL • Released Jan 2006 • JS Lib for Ext. Devs • Small Filesize • Reduce Complexity • Short, concise, code • JS Lib Test Suites • Extensible via plugins • Integration, better coverage
  • 3. Libraries are... • ...abstractions away from existing APIs • ...giving us new APIs to interface with
  • 4. Hypothesis • APIs breed patterns • Libraries build new patterns on top of existing APIs • New library patterns advance development in meaningful, considerable, ways
  • 5. Why Create A Library? • Distance ourselves from repetition • In JavaScript: • Distance from browser differences • In C (stdlib): • Distance from platform differences
  • 6. DOM API • Implemented in every modern browser • Most stable of all the JavaScript APIs • Very well documented
  • 7. Fails in IE 7 JavaScript: document.getElementById(“obj”) .getElementsByTagName(“*”) HTML: <object id=”obj”> <param name="src" value="test.mov"/> <param name="title" value="My Video"/> </object>
  • 8. Fails in Safari 2 JavaScript: document.getElementById(“opt”).selected HTML: <div style=”display: none;”> <select><option id=”opt” value=”test”/></select> </div>
  • 10. Fails in Opera & IE JavaScript: document.getElementById(“q”) HTML: <form action="" method="POST"> <input type="text" name="q"/> <span id="q">Search</span> </form>
  • 11. Fails in Opera & IE JavaScript: var f = document.getElementsByTagName(“input”); for ( var i = 0; i < f.length; i++ ) { ... } HTML: <form action="" method="POST"> Num Rows: <input type="text" id="length" value="22"/><br/> <input type="submit" value="Generate"/> </form>
  • 12. Re-interpretation of the Spec
  • 13. Fails in All JavaScript: document.getElementById(“name”) .setAttribute(“disabled”, false); HTML: <input type=”text” id=”name” disabled=”disabled”/>
  • 16. Why are Libraries Created? • Browsers have a large number of strange differences... • IE has a lot of well documented bugs • Safari has less, but more obscure, bugs • APIs don’t do what you expect • When the API is impossible to learn, but through experience
  • 17. Break down into Meta-Problems • Waiting for the document to load • Traversing the DOM • Injecting HTML into a page
  • 18. Waiting for the DOM to load • A DOM document must be fully loaded before you can work with it • Waiting for the window to load causes flashes of un-effected content
  • 19. Focusing an input <input type=”text” id=”test”/> <script>document.getElementById(“test”).focus();</script> <head><script src=”script.js”</head> $(document).ready(function(){ $(“#test”).focus(); });
  • 20. Traversing the DOM • getElementsByTagName, getElementById, getAttribute, nextSibling, previousSibling, parentNode, className, etc. • A lot to learn and get right • Has the potential to be very tricky (and long-winded)
  • 21. DOM Selectors • Goal: Improve the DOM Traversal API • Provide an API on top of the existing DOM API • Look to standards for inspiration
  • 22. Types of Selectors • XPath Selectors • //div/span[2] • /html[@id=’home’] • CSS 3 Selectors • div > span:nth-of-type(2) • html:root#home
  • 23. Non-trivial Selectors $(“#menu > li:not(:first-child)”).hide(); $(“ul[ul]”).show(); $(“tr:even”).addClass(“even”);
  • 24. Injecting HTML • Very frustrating problem • Browsers are very tempermental • (Inserting table rows, select options, etc.)
  • 25. HTML Solution • Allow users to insert HTML strings • Convert to DOM nodes on the fly • Inject into the document correctly $(“table tr”).append(“<td>test</td>”); $(“select”).prepend(“<option>test</option>”);
  • 26. • DOM Ready + Selectors + HTML Injection • The dream of true unobtrusive DOM scripting $(document).ready(function(){ $(“select”).append(“<option>None</option>”); });
  • 27. New Expectations • What new expectations emerge out of this new API? $(“ul > li”).click(function(){ $(this).load(“menu.html”); }); <ul> <li>item a</li> <li>item b</li> </ul>
  • 28. The Perception • When the document was ready: • We bound an event to a set of elements • We loaded some new elements • Why don’t they have the event?
  • 29. New Pattern: Behaviors function handleClick() { $(“li”, this).click(loadMenu); } function loadMenu() { $(this).load(“menu.html”, handleClick); } $(document).ready(function(){ $(document).each(handleClick); });
  • 31. Pure DOM function handleClick( elem ) { var li = elem.getElementsByTagName(“li”); for ( var i = 0; i < li.length; i++ ) li[i].addEventListener( “click”, loadMenu, false ); Doesn’t exist in IE } function loadMenu() { IE sets the wrong context var elem = this; Doesn’t exist in IE = new XMLHttpRequest(); var xhr xhr.open( “GET”, “menu.html”, false ); xhr.onreadystatechange = function(){ Leaks in IE if ( xhr.readyState == 4 ) { elem.innerHTML = xhr.responseText; handleClick( elem ); } }; xhr.send( null ); } window.onload = function(){ Doesn’t happen immediately var ul = document.getElementsByTagName(“ul”); for ( var i = 0; i < ul.length; i++ ) handleClick( ul[i] ); };
  • 32. FUEL • JavaScript Library for Firefox Extension Development • Designed to be used by Web Developers • Current API is very C++ centric
  • 33. Mozilla: Preferences var prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); var str = Components.classes["@mozilla.org/supports-string;1"] .createInstance(Components.interfaces.nsISupportsString); str.data = "some non-ascii text"; prefs.setComplexValue("preference.with.non.ascii.value", Components.interfaces.nsISupportsString, str);
  • 35. SELECT * FROM users WHERE id = 5; SQL $res = mysql_query(“SELECT * FROM users WHERE id = 5;”); Programming Language while ( $row = mysql_fetch_assoc($res) ) { // etc. Interface } User.find(5) Abstraction Layer (ORM)
  • 36. class Account < ActiveRecord::Base has_many :people do def find_or_create_by_name(name) first_name, last_name = name.split(" ", 2) find_or_create_by_first_name_and_last_name (first_name, last_name) end end end person = Account.find(:first).people .find_or_create_by_name("David Heinemeier Hansson") person.first_name # => "David" person.last_name # => "Heinemeier Hansson"
  • 37. Conclusion • Libraries build new patterns on top of existing APIs • New library patterns advance development in meaningful, considerable, ways
  • 38. Bonus: Meta-Libraries • Domain Specific Languages (DSLs) • Build upon existing libraries building new languages out of their APIs • “jQuery2” meta language: http://ejohn.org/apps/jquery2/
  • 39. More info... • http://ejohn.org/ • http://jquery.com/ • http://wiki.mozilla.org/FUEL • http://ejohn.org/apps/jquery2/ • Contact: [email protected]