SlideShare une entreprise Scribd logo
1  sur  65
Télécharger pour lire hors ligne
dojo.Patterns
                 (for Lovers of JavaScript)




   Peter Higgins (dante)
Dojo Toolkit Project Lead
 jsconf 2009 - Apr 24, 25
Me.

http://dante.dojotoolkit.org
http://twitter.com/phiggins
The History of Dojo
      (cliffnotes version)
Alex Russell
“netwindows”
A Foundation.
A Team.
What is Dojo?

• A JavaScript Toolkit
  - Light-weight Base (6k - 26k)
     - ~30k in 1.4 (plugd)
  - Use at will Library
http://xkcd.com/353
Charts?
Charts?




dojo.require(“dojox.charting”)
Calendars?
Calendars?
dojo.require(“dijit.form.DateTextBox”)
File Uploads?
File Uploads?
dojo.require(“dojox.form.FileUpload”)
Syntax Highlighting?
Syntax Highlighting?
dojo.require(“dojox.highlight”)
... On and On
... On and On
It adds up.
Dojo Build System
All-in-One

• Works transparently with Package System
• Group modules into ‘layers’
• Concatenate CSS @import into ‘layers’
• Layer & File minification
   - Comments, Whitespace, newlines ...
• stripConsole (console.warn, .log, .error)
Firebug Lite
Package / Module Loading

• dojo.require(“some.module”)
• dojo.addOnLoad(function(){ ... })
• dojo.registerModulePath(“my”, “../../my/”)
• dojo.require(“my.code”)
• dojo.provide(“my.code”)
#ifdef in JavaScript?

// the code:
//>>excludeStart(“something”, kwArgs.condition == true);
/* code to exclude */
//>>excludeStop(“something”);


# exclude it:
./build.sh condition=true profile=myprofile
Special Builds

 • Stubs (6k dojo.js)
 • Base++ (dojo.js with modules)
 • Cross-Domain
 • plugd
 • Scope Burning
MooJo?
scopeMap + kwArgs


     // Dojo?
     Moo.load(function(){
     
    place(quot;<p>Hello, Moojo</p>quot;, quot;containerquot;);
     
    query(quot;pquot;)
     
    
 .style(quot;fontSizequot;, quot;10pxquot;)
     
    
 .animate({
     
    
 
 fontSize:{ end: 42 }
     
    
 })
          ;
     });




http://dante.dojotoolkit.org/static/otherlibs/moojo.html
//>>excludeStart(“auto”, kwArgs.autoConflict == “on”)
     if(dojo.config.conflict){
     //>>excludeStop(“auto”)

          // exportNS is a plugd plugin
          dojo.exportNS(dojo, dojo.global);

     //>>excludeStart(“auto”, kwArgs.autoConflict == “on”)
     }
     //>>excludeStop(“auto”)




http://dante.dojotoolkit.org/static/otherlibs/moojo.html
TaskSpeed

  • Written by Authors
  • Fair before Right
  • An interesting start
  • Charts Available*


* http://dante.dojotoolkit.org/taskspeed/report/charts.html
It’s JUST JavaScript
Plain JavaScript

 • JavaScript should have:
    - dojo.indexOf / forEach / map / filter
    - hitch / partial (we get bind()!)
    - declare / delegate / mixin / extend
 • Design Philosophy
    - Defense: Namespaces / Globals
    - Offense: Forward Thinking APIs
Forward Thinking


 // Defer to native trim if available
 dojo.trim = String.prototype.trim ?
    function(str){ return str.trim() } :
    function(str){ /* slightly longer regexp version */ }

 // Mimic Mozilla Array methods:
 dojo.forEach = function(array, callback, scope){ ... }
 dojo.map = function(array, callback, scope){ ... }
 dojo.filter = function(array, callback, scope){ ... }
DojoType (the project)

   // put Dojo Array methods on all Array’s
   dojo._clobber(Array.prototype, {
      forEach: function(callback, scope){
         dojo.forEach(this, callback, scope);
         return this;
      },
      map: function(callback, scope){
         return dojo.map(this, callback, scope);
      }
   });

   // use the new ‘native’ functions:
   [1,2,3,4,5].map(function(i){ return i % 2 === 0 })
      .forEach(function(val){ /* do something */ });




http://code.google.com/p/dojotype
Base at a glance



cheat sheet available: http://download.dojotoolkit.org/current-stable/cheat.pdf
Events, Ajax, FX, DOM

• dojo.connect(node, “onclick”, function(){ });
• dojo.connect(obj, “custom”, obj, “sync”);
• dojo.xhrPost({ form:”login”, load:function(data){ ... } });
• dojo.xhrGet({ url:”foo.txt”, load:function(data){ ... } });
• dojo.anim(node, { width:200 });
• dojo.fadeIn({ node: node }).play();
• dojo.style(n, “height”, “50px”);
• dojo.place(“<p>Hi</p>”, dojo.body());
CSS Selectors

• dojo.query(“ul > li”).addClass(“listy”);
• dojo.query(“a”).onclick(function(){ });
• dojo.query(“tr td + td”).forEach(function(n){ });
• dojo.query(“.someClass”).map(function(n){ .. });
• dojo.NodeList.prototype / dojo.extend
Basic Patterns
Magic Arguments


 // function signatures with defaults
 my.func = function(args){
    var opts = dojo.mixin({
        prop:”foo”
    }, args || {});
    console.log(opts.prop);
 }

 my.func(); // “foo”
 my.func({ prop:”bar” }); // “bar”
DOM Arguments


 var n = document.getElementById(“someId”);
 n.style.width = “200px”;

 // pattern: dojo.byId
 var n = dojo.byId(“someId”)
 // pick:
 dojo.style(n, “width”, “200px”);
 dojo.style(“someId”, “width”, “200px”);
 dojo.query(“#someId”).style(“width”, “200px”);
DOM Arguments


// Accept a String ID or DomNode Reference
my.func = function(node, args){
   node = dojo.byId(node);
   var opts = dojo.mixin({
       prop:”foo”
   }, args||{});
   console.log(opts.prop);
}

my.func(“someId”); // “foo”
my.func(nodeRef, { prop:”bar” }); // “bar”
Ambiguous Constructors (poj)

 some.Thing = function(args, node){
    dojo.mixin(this, args);
 }
 dojo.extend(some.Thing, {
    opt:”a-default”,
    method: function(){
         console.log(this.opt);
    }
 });

 var a = new some.Thing(), b = new some.Thing({ opt:”x” });
 a.opt == “a-default”
 b.opt == “x”
Ambiguous Constructors (declare)


 // allows for simulated inheritance
 dojo.declare(“some.Thing”, null, {
     opt:”a-default”,
     constructor: function(args, node){
         dojo.mixin(this, args);
     }
 });

 var a = new some.Thing(), b = new some.Thing({ opt:”x” });
 a.opt == “a-default”
 b.opt == “x”
Ambiguous Constructors


 // uses the patterns:
 dojo.require(“dojo.parser”);

 <!-- in html -->
 <div id=”baz” dojoType=”some.ClassThing” prop=”value”></div>

 // or without parsing - “poj”
 new some.ClassThing({ prop:”value” }, “baz”);

 // or from no DOM at all
 new some.ClassThing({}).placeAt(“container”);
DRY: Functional JS


 my.turnIt = function(dir){
    // if 1, go next. -1, go left.
 }

 var next = dojo.partial(my.turnIt, 1),
     prev = dojo.partial(my.turnIt, -1);

 // later
 dojo.query(“.nextbutton”).onclick(next);
Dual Service Functions

 my.func = function(node, args){
   node = dojo.byId(node); // Sting|DomNode
   /* do something to node */
 }

 dojo.extend(dojo.NodeList, {
    // now a plugin:
    func: dojo.NodeList._adaptAsForEach(my.func)
 });

 // run one, run all
 my.func(“someId”, { opts:true });
 dojo.query(“.someNodes”).func({ opts:true })
Chaining

 // NodeList:
 dojo.query(“.bar”)
    .addClass(“baz”)
    .onclick(fn)
    .place(“#foo”, “before”)
    .blah().blah().blah().blah(n).blah();

 // Elsewhere
 new dojox.gfx.Shape(surface)
    .addFill(“#ededed”).setStroke(...).connect(...);

 // really just “this”
$ vs PlugD


- Dojo - dojo.query(“.class”) dojo.byId(“id”)
- jQuery - $(“.class”) $(“#id”)
- Prototype - $$(“.class”) $(“id”)
- MooTools - $$(“.class”) $(“id”)
$ vs PlugD


 dojo.conflict();
 $(document).ready(function(){
    $(“#bar”).onclick(fn);
 });

 // or automatically:
 var djConfig = { conflict: true };

 # automatically via build:
 ./build.sh autoConflict=on profile=plugd
Expansion Patterns
dojo.Deferred

• from Twisted/Python
• ASYNC Contract
• Chained Callbacks
• Scope-Aware
Indirect Usage

 // plain xhr
 dojo.xhrGet({
    url:”foo.html“,
    load: function(data){
       /* handle response */
    }
 });

 // manipulating scope
 dojo.xhrGet({
    url:”foo.html”,
    error: dojo.hitch(otherScope, function(e){
       this.logError(e);
    })
 });
Why embed?
 // plain xhr
 dojo.xhrGet({
    url:”foo.html“,
    load: function(data){
       /* handle response */
       dojo.xhrPost({
          form:”bar”,
          content: data,
          load:function(){
             // then update some ui, add another callback ...
             // “ugh”
          }
       })
    }
 });
More ‘Direct’ Usage

 var d = dojo.xhrGet({ url:”foo.html“ })
    .addCallback(function(data){
       // can modify data along response chain
       return data.toLowerCase();
    })
    .addCallback(andPost) // a function that handles data
    .addErrback(otherScope, “errHandler”);

 // elsewhere:
 d.addCallback(function(data){
    /* handle it, return nothing */
 });
dojo.data

• More than just DOM
• API at the core
  - Read, Write, Identity, Notification
• Common Functions and Callbacks
• Direct communication
• RESTful
Store Example?

 // load the store:
 dojo.require(“dojox.data.GoogleServiceStore”);

 // make the store:
 var store = new dojox.data.GoogleSearchStore(...);

 store.fetch({
      // the request:
      query:{ q:”Dojo” },
      // the “wiring”
      onItem: dojo.hitch(thinger, “addItem”),
      onComplete: dojo.hitch(thinger, “render”)
 });
http://persevere.sitepen.com/stocker.html
dojox.data Stores:
 • AndOrReadStore     • FlickrRestStore /
 • AppStore             FlickrStore
                      • GoogleFeedStore
 • AtomReadStore
                      • GoogleSearchStore
 • CouchDBRestStore
                      • HtmlStore
 • CssRuleStore
                      • jsonPathStore
 • CsvStore
                      • jsonRestStore
 • FileStore
                      • OpmlStore
Data Consumers:
RPC / SMD
SMD


 dojo.require(“dojox.rpc.Service”);

 var goog = new dojox.rpc.Service(“google.smd”);

 goog.websearch({ q:”Dojo” }).addCallback(function(response){
    // handle the responses
 });

 goog.booksearch({ q:”Dojo” }).addBoth(function(response){
    // Books about Dojo
 });
The Dojo Toolkit


• Long standing Development
• Large, Active Developer Base
• Friendly Professional Community
• Liberally Licensed, Clean IP




http://dojotoolkit.org http://dojofoundation.org
Questions?
Me, Again.
    dante@dojotoolkit.org
 http://twitter.com/phiggins
http://higginsforpresident.net/

Contenu connexe

Tendances

Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterpriseDave Artz
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery BasicsKaloyan Kosev
 
The Dojo Toolkit An Introduction
The Dojo Toolkit   An IntroductionThe Dojo Toolkit   An Introduction
The Dojo Toolkit An IntroductionJeff Fox
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseAaron Silverman
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapWebFrameworks
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojoyoavrubin
 
Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0James Thomas
 
Data presentation with dust js technologies backing linkedin
Data presentation with dust js   technologies backing linkedinData presentation with dust js   technologies backing linkedin
Data presentation with dust js technologies backing linkedinRuhaim Izmeth
 
HTML5와 오픈소스 기반의 Web Components 기술
HTML5와 오픈소스 기반의 Web Components 기술HTML5와 오픈소스 기반의 Web Components 기술
HTML5와 오픈소스 기반의 Web Components 기술Jeongkyu Shin
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Dojo javascript toolkit
Dojo javascript toolkit Dojo javascript toolkit
Dojo javascript toolkit Predhin Sapru
 

Tendances (20)

Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] Enterprise
 
handout-05b
handout-05bhandout-05b
handout-05b
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
The Dojo Toolkit An Introduction
The Dojo Toolkit   An IntroductionThe Dojo Toolkit   An Introduction
The Dojo Toolkit An Introduction
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Java script
Java scriptJava script
Java script
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash Course
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-Bootstrap
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
 
J query intro_29thsep_alok
J query intro_29thsep_alokJ query intro_29thsep_alok
J query intro_29thsep_alok
 
Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0
 
HTML5 Introduction by Dhepthi L
HTML5 Introduction by Dhepthi LHTML5 Introduction by Dhepthi L
HTML5 Introduction by Dhepthi L
 
Data presentation with dust js technologies backing linkedin
Data presentation with dust js   technologies backing linkedinData presentation with dust js   technologies backing linkedin
Data presentation with dust js technologies backing linkedin
 
HTML5와 오픈소스 기반의 Web Components 기술
HTML5와 오픈소스 기반의 Web Components 기술HTML5와 오픈소스 기반의 Web Components 기술
HTML5와 오픈소스 기반의 Web Components 기술
 
Liking performance
Liking performanceLiking performance
Liking performance
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Dojo javascript toolkit
Dojo javascript toolkit Dojo javascript toolkit
Dojo javascript toolkit
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Aleact
AleactAleact
Aleact
 

Similaire à dojo.Patterns

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesTobias Oetiker
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build Systemklipstein
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsTobias Oetiker
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 

Similaire à dojo.Patterns (20)

Trimming The Cruft
Trimming The CruftTrimming The Cruft
Trimming The Cruft
 
Txjs
TxjsTxjs
Txjs
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Dojo and Adobe AIR
Dojo and Adobe AIRDojo and Adobe AIR
Dojo and Adobe AIR
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
A More Flash Like Web?
A More Flash Like Web?A More Flash Like Web?
A More Flash Like Web?
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 

Plus de Peter Higgins

Plus de Peter Higgins (6)

Jsconf.us.2013
Jsconf.us.2013Jsconf.us.2013
Jsconf.us.2013
 
has("builds")
has("builds")has("builds")
has("builds")
 
has.js
has.jshas.js
has.js
 
Just JavaScript
Just JavaScriptJust JavaScript
Just JavaScript
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
dojo.things()
dojo.things()dojo.things()
dojo.things()
 

Dernier

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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 2024Victor Rentea
 
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
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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...DianaGray10
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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 ...apidays
 
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 DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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 educationjfdjdjcjdnsjd
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
"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 ...Zilliz
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
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 Pakistandanishmna97
 

Dernier (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
+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...
 
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
 
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
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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 ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"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 ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
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
 

dojo.Patterns

  • 1. dojo.Patterns (for Lovers of JavaScript) Peter Higgins (dante) Dojo Toolkit Project Lead jsconf 2009 - Apr 24, 25
  • 3.
  • 4. The History of Dojo (cliffnotes version)
  • 8. What is Dojo? • A JavaScript Toolkit - Light-weight Base (6k - 26k) - ~30k in 1.4 (plugd) - Use at will Library
  • 22. All-in-One • Works transparently with Package System • Group modules into ‘layers’ • Concatenate CSS @import into ‘layers’ • Layer & File minification - Comments, Whitespace, newlines ... • stripConsole (console.warn, .log, .error)
  • 24. Package / Module Loading • dojo.require(“some.module”) • dojo.addOnLoad(function(){ ... }) • dojo.registerModulePath(“my”, “../../my/”) • dojo.require(“my.code”) • dojo.provide(“my.code”)
  • 25. #ifdef in JavaScript? // the code: //>>excludeStart(“something”, kwArgs.condition == true); /* code to exclude */ //>>excludeStop(“something”); # exclude it: ./build.sh condition=true profile=myprofile
  • 26. Special Builds • Stubs (6k dojo.js) • Base++ (dojo.js with modules) • Cross-Domain • plugd • Scope Burning
  • 28. scopeMap + kwArgs // Dojo? Moo.load(function(){ place(quot;<p>Hello, Moojo</p>quot;, quot;containerquot;); query(quot;pquot;) .style(quot;fontSizequot;, quot;10pxquot;) .animate({ fontSize:{ end: 42 } }) ; }); http://dante.dojotoolkit.org/static/otherlibs/moojo.html
  • 29. //>>excludeStart(“auto”, kwArgs.autoConflict == “on”) if(dojo.config.conflict){ //>>excludeStop(“auto”) // exportNS is a plugd plugin dojo.exportNS(dojo, dojo.global); //>>excludeStart(“auto”, kwArgs.autoConflict == “on”) } //>>excludeStop(“auto”) http://dante.dojotoolkit.org/static/otherlibs/moojo.html
  • 30.
  • 31. TaskSpeed • Written by Authors • Fair before Right • An interesting start • Charts Available* * http://dante.dojotoolkit.org/taskspeed/report/charts.html
  • 33. Plain JavaScript • JavaScript should have: - dojo.indexOf / forEach / map / filter - hitch / partial (we get bind()!) - declare / delegate / mixin / extend • Design Philosophy - Defense: Namespaces / Globals - Offense: Forward Thinking APIs
  • 34. Forward Thinking // Defer to native trim if available dojo.trim = String.prototype.trim ? function(str){ return str.trim() } : function(str){ /* slightly longer regexp version */ } // Mimic Mozilla Array methods: dojo.forEach = function(array, callback, scope){ ... } dojo.map = function(array, callback, scope){ ... } dojo.filter = function(array, callback, scope){ ... }
  • 35. DojoType (the project) // put Dojo Array methods on all Array’s dojo._clobber(Array.prototype, { forEach: function(callback, scope){ dojo.forEach(this, callback, scope); return this; }, map: function(callback, scope){ return dojo.map(this, callback, scope); } }); // use the new ‘native’ functions: [1,2,3,4,5].map(function(i){ return i % 2 === 0 }) .forEach(function(val){ /* do something */ }); http://code.google.com/p/dojotype
  • 36. Base at a glance cheat sheet available: http://download.dojotoolkit.org/current-stable/cheat.pdf
  • 37. Events, Ajax, FX, DOM • dojo.connect(node, “onclick”, function(){ }); • dojo.connect(obj, “custom”, obj, “sync”); • dojo.xhrPost({ form:”login”, load:function(data){ ... } }); • dojo.xhrGet({ url:”foo.txt”, load:function(data){ ... } }); • dojo.anim(node, { width:200 }); • dojo.fadeIn({ node: node }).play(); • dojo.style(n, “height”, “50px”); • dojo.place(“<p>Hi</p>”, dojo.body());
  • 38. CSS Selectors • dojo.query(“ul > li”).addClass(“listy”); • dojo.query(“a”).onclick(function(){ }); • dojo.query(“tr td + td”).forEach(function(n){ }); • dojo.query(“.someClass”).map(function(n){ .. }); • dojo.NodeList.prototype / dojo.extend
  • 40. Magic Arguments // function signatures with defaults my.func = function(args){ var opts = dojo.mixin({ prop:”foo” }, args || {}); console.log(opts.prop); } my.func(); // “foo” my.func({ prop:”bar” }); // “bar”
  • 41. DOM Arguments var n = document.getElementById(“someId”); n.style.width = “200px”; // pattern: dojo.byId var n = dojo.byId(“someId”) // pick: dojo.style(n, “width”, “200px”); dojo.style(“someId”, “width”, “200px”); dojo.query(“#someId”).style(“width”, “200px”);
  • 42. DOM Arguments // Accept a String ID or DomNode Reference my.func = function(node, args){ node = dojo.byId(node); var opts = dojo.mixin({ prop:”foo” }, args||{}); console.log(opts.prop); } my.func(“someId”); // “foo” my.func(nodeRef, { prop:”bar” }); // “bar”
  • 43. Ambiguous Constructors (poj) some.Thing = function(args, node){ dojo.mixin(this, args); } dojo.extend(some.Thing, { opt:”a-default”, method: function(){ console.log(this.opt); } }); var a = new some.Thing(), b = new some.Thing({ opt:”x” }); a.opt == “a-default” b.opt == “x”
  • 44. Ambiguous Constructors (declare) // allows for simulated inheritance dojo.declare(“some.Thing”, null, { opt:”a-default”, constructor: function(args, node){ dojo.mixin(this, args); } }); var a = new some.Thing(), b = new some.Thing({ opt:”x” }); a.opt == “a-default” b.opt == “x”
  • 45. Ambiguous Constructors // uses the patterns: dojo.require(“dojo.parser”); <!-- in html --> <div id=”baz” dojoType=”some.ClassThing” prop=”value”></div> // or without parsing - “poj” new some.ClassThing({ prop:”value” }, “baz”); // or from no DOM at all new some.ClassThing({}).placeAt(“container”);
  • 46. DRY: Functional JS my.turnIt = function(dir){ // if 1, go next. -1, go left. } var next = dojo.partial(my.turnIt, 1), prev = dojo.partial(my.turnIt, -1); // later dojo.query(“.nextbutton”).onclick(next);
  • 47. Dual Service Functions my.func = function(node, args){ node = dojo.byId(node); // Sting|DomNode /* do something to node */ } dojo.extend(dojo.NodeList, { // now a plugin: func: dojo.NodeList._adaptAsForEach(my.func) }); // run one, run all my.func(“someId”, { opts:true }); dojo.query(“.someNodes”).func({ opts:true })
  • 48. Chaining // NodeList: dojo.query(“.bar”) .addClass(“baz”) .onclick(fn) .place(“#foo”, “before”) .blah().blah().blah().blah(n).blah(); // Elsewhere new dojox.gfx.Shape(surface) .addFill(“#ededed”).setStroke(...).connect(...); // really just “this”
  • 49. $ vs PlugD - Dojo - dojo.query(“.class”) dojo.byId(“id”) - jQuery - $(“.class”) $(“#id”) - Prototype - $$(“.class”) $(“id”) - MooTools - $$(“.class”) $(“id”)
  • 50. $ vs PlugD dojo.conflict(); $(document).ready(function(){ $(“#bar”).onclick(fn); }); // or automatically: var djConfig = { conflict: true }; # automatically via build: ./build.sh autoConflict=on profile=plugd
  • 52. dojo.Deferred • from Twisted/Python • ASYNC Contract • Chained Callbacks • Scope-Aware
  • 53. Indirect Usage // plain xhr dojo.xhrGet({ url:”foo.html“, load: function(data){ /* handle response */ } }); // manipulating scope dojo.xhrGet({ url:”foo.html”, error: dojo.hitch(otherScope, function(e){ this.logError(e); }) });
  • 54. Why embed? // plain xhr dojo.xhrGet({ url:”foo.html“, load: function(data){ /* handle response */ dojo.xhrPost({ form:”bar”, content: data, load:function(){ // then update some ui, add another callback ... // “ugh” } }) } });
  • 55. More ‘Direct’ Usage var d = dojo.xhrGet({ url:”foo.html“ }) .addCallback(function(data){ // can modify data along response chain return data.toLowerCase(); }) .addCallback(andPost) // a function that handles data .addErrback(otherScope, “errHandler”); // elsewhere: d.addCallback(function(data){ /* handle it, return nothing */ });
  • 56. dojo.data • More than just DOM • API at the core - Read, Write, Identity, Notification • Common Functions and Callbacks • Direct communication • RESTful
  • 57. Store Example? // load the store: dojo.require(“dojox.data.GoogleServiceStore”); // make the store: var store = new dojox.data.GoogleSearchStore(...); store.fetch({ // the request: query:{ q:”Dojo” }, // the “wiring” onItem: dojo.hitch(thinger, “addItem”), onComplete: dojo.hitch(thinger, “render”) });
  • 59. dojox.data Stores: • AndOrReadStore • FlickrRestStore / • AppStore FlickrStore • GoogleFeedStore • AtomReadStore • GoogleSearchStore • CouchDBRestStore • HtmlStore • CssRuleStore • jsonPathStore • CsvStore • jsonRestStore • FileStore • OpmlStore
  • 62. SMD dojo.require(“dojox.rpc.Service”); var goog = new dojox.rpc.Service(“google.smd”); goog.websearch({ q:”Dojo” }).addCallback(function(response){ // handle the responses }); goog.booksearch({ q:”Dojo” }).addBoth(function(response){ // Books about Dojo });
  • 63. The Dojo Toolkit • Long standing Development • Large, Active Developer Base • Friendly Professional Community • Liberally Licensed, Clean IP http://dojotoolkit.org http://dojofoundation.org
  • 65. Me, Again. dante@dojotoolkit.org http://twitter.com/phiggins http://higginsforpresident.net/