SlideShare une entreprise Scribd logo
1  sur  43
IT’S JUST JAVASCRIPT.
   Peter Higgins / @phiggins / #txjs / 2010-06-04
ME.
DOJO.
http://dojotoolkit.org
yay Dojo.


A Library.

5+ years testing, revision, support.

Backwards compatible APIs (to a painful degree)
IN THE END ...
  It’s just a LOT of JavaScript.
IN THE END ...
 It’s just a LOT of modular JavaScript.
IN THE END ...
 It’s just a LOT of optional JavaScript.
JAVASCRIPT IS MAGIC.
MORE THAN JUST TEH DOM
pub/sub, ftw.



ambiguous coupling

cometd
dojo.subscribe("/hello/world", function(){

     console.warn(arguments);
});


dojo.publish("/hello/world", ["foo", "bar"]);


Also availabile for jQuery:
http://higginsforpresident.net/js/static/jq.pubsub.js
OO / CLASSY
dojo.declare("Thing", [inheritance, chain], {

     myProps:"override",

     aMethod:function(){

     
   this.inherited(arguments);

     }
});


new Thing();
`THIS` IS MAGIC.
.CALL / .APPLY
var obj = { b:2 }
var obj2 = {

   b:1,

   foo: function(num){ this.b += num; return this.b; }
}


obj2.foo(1); // 2
obj2.foo.call(obj, 3); // 5
obj2.foo.apply(obj, [3]); // 5
curry, bind, hitch, partial, etc



Scope/context manipulation via apply/call. Simple wrapper.

promotes code re-use / DRY
// partial is to curry ...
var foo = function(direction){

       if(direction){ goleft(); }else{ goright(); }
}
var left = foo.curry(1),
    right = dojo.partial(foo, 0)
    ;


    left(); right();
// as bind is to hitch
var o = {

    handler:function(response){ ... },

    send:function(){

    
      dojo.xhrPost({

    
      
    url:"/the/url",

    
      
    handle: dojo.hitch(this, "method")

    
      })

    }
};
o.send();
ALSO FOR JQUERY ...
  http://higginsforpresident.net/js/static/jq.hitch.js
DUCK PUNCH
   aka: AOP
(function(d){


    var oldonload = d.addOnLoad;

    d.addOnLoad = d.ready = function(fn){

    
 oldonload.call(d, d.partial(fn, d));

    }


    // now you can use `dojo` as whatever first

    // arg to dojo.ready callback is:

    //

    //
 dojo.ready(function(d){

    //
 
 d.require("foo.bar.Baz");

    //
 });

})(dojo);
(function(d){

    var rqr = d.require;

    d.require = function(module){

    
      if(d.isArray(module)){

    
      
   d.forEach(module, rqr, d);

    
      }else{

    
      
   rqr.apply(d, arguments);

    
      }

    
      return d; // mmm chaining.

    }
})(dojo);
// old api:
dojo.require(“foo.Bar”);
// new ducked apis:
dojo.require([“foo.Bar”, “bar.Baz”]);
dojo.require(“bam.Foo”).require(“omg.Really”)
  .require([“oh.Right”, “doit.ThisWayToo”])
  ;
(function(d){
   // replace the old dojo with a function

      var d = dojo;

      dojo = function(a){

      
 if(d.isFunction(a)){

      
 
 d.ready(a);

      
 
 return dojo;

      
 }else{

      
 
 return d.query.apply(d, arguments);

      
 }

      }


      // this is just to bother alex:

      dojo.fn = d.NodeList.prototype;


      // mix dojo back into itself.

      for(var i in d){ dojo[i] = d[i]; }

})(dojo);
dojo(function(){ /* onload */});

dojo("#someId").style({ color:”red” }).onclick(fn);

dojo.style("someId", { color:”red” });

dojo.fn.myRadPlugin = function(){
  return this.forEach(...);
}
Ubiquitous Unicorn.
NATIVE PROTOTYPES
      for fun and profit.
if(!Array.prototype.forEach){

     Array.prototype.forEach = function(cb, thisObj){

     
 thisObj = thisObj || window;

     
 for(var i = 0, l = this.length; i < l; i++){

     
 
 cb.call(thisObj, ar[i], i, ar);

     
 }

     }
}

[1,2,3].forEach(function(num){ alert(num); });
if(!Array.prototype.forEach){

    Array.prototype.forEach = function(cb){

    
    for(var i = 0, l = this.length; i < l; i++){

    
    
    cb.call(ar[i], i, ar);

    
    }

    }
}
[1,2,3].forEach(function(){ alert(this); });
DOJOTYPE!
http://code.google.com/p/dojotype
1:1.333333 Mapping to Dojo
Base Dojo

dojo.date

dojo.string

dojo.Color
(function(d){


    var c = new d.Color(),

    
 setup = function(meth){

    
 
 if(!this[meth]){

    
 
 
 this[meth] = function(){

    
 
 
 
 c.setColor(this);

    
 
 
 
 return c[meth].apply(c, arguments);

    
 
 
 };

    
 
 }

    
 }

    ;


    d.forEach(["toRgb", "toRgba", "toHex"], setup, String.prototype);

    d.forEach(["toCss"], setup, Array.prototype);

       // [255,255,255].toCss(); // returns #000000
       // “#000000”.toRgb(); // returns [255,255,255]

})(dojo);
LAME MODERN BROWSERS
        “win”.blink()
es3ex-String!
          http://code.google.com/p/dojotype/source/browse/trunk/es3ex-String.js




.anchor(), .link(), .fontsize, .fontcolor

  node.innerHTML = “click here”.link(“http://google.com”);

blink(), sup(), small(), et al.
new Date()


i18n

formatting

comparison

addition
var dd = d.date, dp = Date.prototype,

   
     map = {

   
     
     "daysInMonth": [dd, "daysInMonth"],

   
     
     "isLeapYear": [dd, "isLeapYear"],

   
     
     "timezone": [dd, "getTimezoneName"],

   
     
     "compare": [dd, "compare"],

   
     
     "add": [dd, "add"],

   
     
     "difference": [dd, "difference"],

   
     
     "format": [dd.locale, "format"],

   
     
     "isWeekend": [dd.locale, "isWeekend"]

   
     }

   ;


   // setup all the above direct mappings

   var setup = function(pn, fn){

   
      if(!dp[pn]){

   
      
       var fullfn = fn[0][fn[1]];

   
      
       dp[pn] = function(){

   
      
       
      return fullfn.apply(fn[0], d._prep(this, arguments));

   
      
       };

   
      }

   };


   for(var i in map){ setup(i, map[i]); }
d._clobber(Date.prototype, {

   
     json: function(){

   
     
       // summary: Serializes a Date object as an ISO String. Helps

   
     
       // when serializing a JSON string from an object containing

   
     
       // Date objects.

   
     
       return d.date.stamp.toISOString(this, { selector: 'date' });

   
     }

   });


   d._clobber(String.prototype, {

   
     toDate: function(options){

   
     
     // summary: Convert this string into a Date object, provided it is formatted properly.

   
     
     return dojo.date.locale.parse(this, options);

   
     }

   });
var maff = Math, np = Number.prototype;

   d.forEach(

   
     [

   
     
      // a list of straight-up-shit-that-could-be-on-Number

   
     
      // that would just call Math.something(this)

   
     
      "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "log",

   
     
      "max", "min", "pow", /* "random", "round", */ "sin", "sqrt", "tan"

   
     ],

   
     function(meth){

   
     
      // setup the function in place if it doesn't exist

   
     
      // for some reason

   
     
      if(!this[meth] && maff[meth]){

   
     
      
        this[meth] = function(param){

   
     
      
        
      // if we have at least one extra param, take the whole thing:

   
     
      
        
      return maff[meth].apply(maff, param ? d._prep(this, arguments) : [this]);

   
     
      
        };

   
     
      }

   
     },

   
     np // context

   );
JUST JAVASCRIPT.
       Still.
Take Away:

JavaScript is fun and flexible.

The DOM is the culprit. and evil.

Because you can do something, doesn’t mean you should.

  Don’t let that stop you.

Embrace the language as a whole.
THANKS!
clap. or ask questions. or don’t.
@PHIGGINS
 http://higginsforpresident.net

Contenu connexe

Tendances

Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
Lin Yo-An
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
Jason Hanson
 

Tendances (20)

Groovy
GroovyGroovy
Groovy
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Naughty And Nice Bash Features
Naughty And Nice Bash FeaturesNaughty And Nice Bash Features
Naughty And Nice Bash Features
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
AST Rewriting Using recast and esprima
AST Rewriting Using recast and esprimaAST Rewriting Using recast and esprima
AST Rewriting Using recast and esprima
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
When RegEx is not enough
When RegEx is not enoughWhen RegEx is not enough
When RegEx is not enough
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Troubleshooting Puppet
Troubleshooting PuppetTroubleshooting Puppet
Troubleshooting Puppet
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 

En vedette (8)

Photography
PhotographyPhotography
Photography
 
Yui conf nov8-2010-introtoyql
Yui conf nov8-2010-introtoyqlYui conf nov8-2010-introtoyql
Yui conf nov8-2010-introtoyql
 
Contributing to YUI
Contributing to YUIContributing to YUI
Contributing to YUI
 
Photography
PhotographyPhotography
Photography
 
My bestiessss
My bestiessssMy bestiessss
My bestiessss
 
YUI 3: Below the Surface
YUI 3: Below the SurfaceYUI 3: Below the Surface
YUI 3: Below the Surface
 
oEmbed と Text::Hatena
oEmbed と Text::HatenaoEmbed と Text::Hatena
oEmbed と Text::Hatena
 
7 Habits of Exceptional Performance
7 Habits of Exceptional Performance7 Habits of Exceptional Performance
7 Habits of Exceptional Performance
 

Similaire à Txjs

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 

Similaire à Txjs (20)

dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Trimming The Cruft
Trimming The CruftTrimming The Cruft
Trimming The Cruft
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
Groovy
GroovyGroovy
Groovy
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 

Plus de Peter Higgins (7)

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()
 
Zero To Dojo
Zero To DojoZero To Dojo
Zero To Dojo
 

Dernier

+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@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

+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...
 
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...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
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
 
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)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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?
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Txjs

  • 1. IT’S JUST JAVASCRIPT. Peter Higgins / @phiggins / #txjs / 2010-06-04
  • 2. ME.
  • 4. yay Dojo. A Library. 5+ years testing, revision, support. Backwards compatible APIs (to a painful degree)
  • 5. IN THE END ... It’s just a LOT of JavaScript.
  • 6. IN THE END ... It’s just a LOT of modular JavaScript.
  • 7. IN THE END ... It’s just a LOT of optional JavaScript.
  • 9. MORE THAN JUST TEH DOM
  • 11. dojo.subscribe("/hello/world", function(){ console.warn(arguments); }); dojo.publish("/hello/world", ["foo", "bar"]); Also availabile for jQuery: http://higginsforpresident.net/js/static/jq.pubsub.js
  • 13. dojo.declare("Thing", [inheritance, chain], { myProps:"override", aMethod:function(){ this.inherited(arguments); } }); new Thing();
  • 16. var obj = { b:2 } var obj2 = { b:1, foo: function(num){ this.b += num; return this.b; } } obj2.foo(1); // 2 obj2.foo.call(obj, 3); // 5 obj2.foo.apply(obj, [3]); // 5
  • 17. curry, bind, hitch, partial, etc Scope/context manipulation via apply/call. Simple wrapper. promotes code re-use / DRY
  • 18. // partial is to curry ... var foo = function(direction){ if(direction){ goleft(); }else{ goright(); } } var left = foo.curry(1), right = dojo.partial(foo, 0) ; left(); right();
  • 19. // as bind is to hitch var o = { handler:function(response){ ... }, send:function(){ dojo.xhrPost({ url:"/the/url", handle: dojo.hitch(this, "method") }) } }; o.send();
  • 20. ALSO FOR JQUERY ... http://higginsforpresident.net/js/static/jq.hitch.js
  • 21. DUCK PUNCH aka: AOP
  • 22. (function(d){ var oldonload = d.addOnLoad; d.addOnLoad = d.ready = function(fn){ oldonload.call(d, d.partial(fn, d)); } // now you can use `dojo` as whatever first // arg to dojo.ready callback is: // // dojo.ready(function(d){ // d.require("foo.bar.Baz"); // }); })(dojo);
  • 23. (function(d){ var rqr = d.require; d.require = function(module){ if(d.isArray(module)){ d.forEach(module, rqr, d); }else{ rqr.apply(d, arguments); } return d; // mmm chaining. } })(dojo);
  • 24. // old api: dojo.require(“foo.Bar”); // new ducked apis: dojo.require([“foo.Bar”, “bar.Baz”]); dojo.require(“bam.Foo”).require(“omg.Really”) .require([“oh.Right”, “doit.ThisWayToo”]) ;
  • 25. (function(d){ // replace the old dojo with a function var d = dojo; dojo = function(a){ if(d.isFunction(a)){ d.ready(a); return dojo; }else{ return d.query.apply(d, arguments); } } // this is just to bother alex: dojo.fn = d.NodeList.prototype; // mix dojo back into itself. for(var i in d){ dojo[i] = d[i]; } })(dojo);
  • 26. dojo(function(){ /* onload */}); dojo("#someId").style({ color:”red” }).onclick(fn); dojo.style("someId", { color:”red” }); dojo.fn.myRadPlugin = function(){ return this.forEach(...); }
  • 28. NATIVE PROTOTYPES for fun and profit.
  • 29. if(!Array.prototype.forEach){ Array.prototype.forEach = function(cb, thisObj){ thisObj = thisObj || window; for(var i = 0, l = this.length; i < l; i++){ cb.call(thisObj, ar[i], i, ar); } } } [1,2,3].forEach(function(num){ alert(num); });
  • 30. if(!Array.prototype.forEach){ Array.prototype.forEach = function(cb){ for(var i = 0, l = this.length; i < l; i++){ cb.call(ar[i], i, ar); } } } [1,2,3].forEach(function(){ alert(this); });
  • 32. 1:1.333333 Mapping to Dojo Base Dojo dojo.date dojo.string dojo.Color
  • 33. (function(d){ var c = new d.Color(), setup = function(meth){ if(!this[meth]){ this[meth] = function(){ c.setColor(this); return c[meth].apply(c, arguments); }; } } ; d.forEach(["toRgb", "toRgba", "toHex"], setup, String.prototype); d.forEach(["toCss"], setup, Array.prototype); // [255,255,255].toCss(); // returns #000000 // “#000000”.toRgb(); // returns [255,255,255] })(dojo);
  • 34. LAME MODERN BROWSERS “win”.blink()
  • 35. es3ex-String! http://code.google.com/p/dojotype/source/browse/trunk/es3ex-String.js .anchor(), .link(), .fontsize, .fontcolor node.innerHTML = “click here”.link(“http://google.com”); blink(), sup(), small(), et al.
  • 37. var dd = d.date, dp = Date.prototype, map = { "daysInMonth": [dd, "daysInMonth"], "isLeapYear": [dd, "isLeapYear"], "timezone": [dd, "getTimezoneName"], "compare": [dd, "compare"], "add": [dd, "add"], "difference": [dd, "difference"], "format": [dd.locale, "format"], "isWeekend": [dd.locale, "isWeekend"] } ; // setup all the above direct mappings var setup = function(pn, fn){ if(!dp[pn]){ var fullfn = fn[0][fn[1]]; dp[pn] = function(){ return fullfn.apply(fn[0], d._prep(this, arguments)); }; } }; for(var i in map){ setup(i, map[i]); }
  • 38. d._clobber(Date.prototype, { json: function(){ // summary: Serializes a Date object as an ISO String. Helps // when serializing a JSON string from an object containing // Date objects. return d.date.stamp.toISOString(this, { selector: 'date' }); } }); d._clobber(String.prototype, { toDate: function(options){ // summary: Convert this string into a Date object, provided it is formatted properly. return dojo.date.locale.parse(this, options); } });
  • 39. var maff = Math, np = Number.prototype; d.forEach( [ // a list of straight-up-shit-that-could-be-on-Number // that would just call Math.something(this) "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "log", "max", "min", "pow", /* "random", "round", */ "sin", "sqrt", "tan" ], function(meth){ // setup the function in place if it doesn't exist // for some reason if(!this[meth] && maff[meth]){ this[meth] = function(param){ // if we have at least one extra param, take the whole thing: return maff[meth].apply(maff, param ? d._prep(this, arguments) : [this]); }; } }, np // context );
  • 41. Take Away: JavaScript is fun and flexible. The DOM is the culprit. and evil. Because you can do something, doesn’t mean you should. Don’t let that stop you. Embrace the language as a whole.
  • 42. THANKS! clap. or ask questions. or don’t.

Notes de l'éditeur