JSĒINĒŃĒFISHBOWLHOWĒTOĒFEEDĒYOURĒFISHESĒWITHOUTĒPOLLUTINGĒTHEĒWŃTER© 2013Matteo Carella
“Everything starts with bad water...”
BEFOREvar sizeWidth = $(#sizeHeader).outerWidth();var sizeWidthNoPadding = $(#sizeHeader).width();var sizeTextWidth = $(.s...
OMGÂ
ŃFTERvar$sizeHeader = $(#sizeHeader),$sizeText = $(.sizeText),$sizesUl = $(#sizesUl),$sizesUlLi = $sizesUl.find(li),$sizes...
Dont be a fish. Be a shark.
// VAR CACHINGfirst = $(#first);second = $(#second);// USE A CODING CONVENTION (HUNGARIAN NOTATION)var $first = $(#first);...
// SINGLE VAR PATTERN (putting at the end unassigned vars)var$first = $(#first),$second = $(#second),value = $first.val(),...
// DONT USE DEPRECATED METHODS$first.on(click,function(){$first.css(border,1px solid red);$first.css(color,blue);});// CON...
// USE CHAINING$second.html(value);$second.on(click,function(){alert(hello everybody);}).fadeIn(slow).animate({height:120p...
SHORTCIRCUITING// badfunction initVar($myVar) {if(!$myVar) {$myVar = $(#selector);}}// betterfunction initVar($myVar) {$my...
SHORTCUTS// badif(collection.length > 0){..}// betterif(collection.length){..}
DETŃCHĒELEMENTSĒWHENĒDOINGĒMŃNIPULŃTIONS// badvar$container = $("#container"),$containerLi = $("#container li"),$element =...
DŃTŃĒŃTTRIBUTES// bad$(#id).data(key,value);// better (faster)$.data(#id,key,value);
BEĒSMŃRT// badvar$sizesUl = $(#sizesUl),$sizesUlLi = $(#sizesUl li),$sizesUlLiSpan = $(#sizesUl li span);// better (faster...
Lets talk now about global pollution.
GOLDENĒRULESDont introduce global variables.Dont introduce global functions (unless necessary).Make sure your code doesnt ...
Global vars.Global functions.Global pollution.WTF global means?
MEŃNSĒTHISfunction original() {console.log(original);}function fake() {original = function() { console.log(fake); }}$(docu...
FIRSTĀJSSECONDĀJSfunction hello() {console.log("first");}$(document).ready(function(){hello();});function hello() {console...
OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><scrip...
WHŃTBSĒTHEĒDIFFERENCEĒBETWEENÅfish = "nemo";var fish = "nemo";
EXŃMPLEĀJSvar fish = "nemo"; // global$(document).ready(function(){console.log("I am rrready.");});$(document).ready(funct...
Everything is attached to the global object. In the case ofthe web browser, that is the window object. In JavaScript,funct...
FIRSTĀJSSECONDĀJSvar hello = function() {console.log("first");}$(document).ready(function(){hello();});var hello = functio...
OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><scrip...
SŃMEĒOUTPUTĒŃSĒBEFOREHOLY FISH!
FIRSTĀJSSECONDĀJS$(document).ready(function(){var hello = function() { console.log("first"); }hello();});$(document).ready...
OURĒWEBPŃGE> first, second> second, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><scrip...
ŃŃŃŃHĀFinally.
One useful technique to ensure that your variables andfunctions are self contained is to use an IIFE.
// IIFE: immediately invoked func expression(function(){// still mantain access to globals//private membersreturn{//public...
(function(){// vars declarationvar doStuff = function(args) {// some code}return{doThings: function(arga,argb,argc) {..},o...
It keeps code to a minimum.It provides a closure which prevents naming conflicts.It’s good for encapsulation.It’s good for...
So...What about this?
FIRSTĀJS(function(){var init = function(){console.log(first);};if (typeof $M === undefined) {$M = {};}$M.module = init;})(...
SECONDĀJS(function(){var init = function(){console.log(second);};if (typeof $M === undefined) {$M = {};}$M.module = init;}...
OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><scrip...
OMGÂÂĒSTILLĒYOUÂÅYes, same namespace.
ŃĒQUICKĒRECŃP
// GLOBALSfunction doThings() { console.log("do things"); }var things = "things";$(document).ready(function(){// LOCALSfun...
So, again...What about this?
(function () {things = "things";function doThings() { console.log("do things"); }})();$(document).ready(function(){console...
PLEŃSEAlways put var before any declaration.
HOISTINGundefined != not defined
$(document).ready(function () {console.log($el); // undefined (declared but unassigned)console.log($some) // reference err...
$(document).ready(function () {var $el, $node; // declarationif(Navigation.SUBSECTION == "index"){$el = $(#element); // as...
Functions are affected by hoisting too.But that is another story...
Questions?Ask Google :)
THŃNKĒYOUĀPlease, dont be an . Ask me before reusing these slides.Matteo Carella © 2013ass
Javascript in a fishbowl
Javascript in a fishbowl
Javascript in a fishbowl
Upcoming SlideShare
Loading in …5
×

Javascript in a fishbowl

3,081 views
2,428 views

Published on

Published in: Technology, Design
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,081
On SlideShare
0
From Embeds
0
Number of Embeds
21
Actions
Shares
0
Downloads
0
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

Javascript in a fishbowl

  1. JSĒINĒŃĒFISHBOWLHOWĒTOĒFEEDĒYOURĒFISHESĒWITHOUTĒPOLLUTINGĒTHEĒWŃTER© 2013Matteo Carella
  2. “Everything starts with bad water...”
  3. BEFOREvar sizeWidth = $(#sizeHeader).outerWidth();var sizeWidthNoPadding = $(#sizeHeader).width();var sizeTextWidth = $(.sizeText).width();$(ul#sizesUl, ul#sizesUl li).width(sizeWidth);$(#sizeHeader).width(sizeWidthNoPadding);$(.sizeText, ul#sizesUl li span).width(sizeTextWidth);$(ul#sizesUl li span).on(click, function(){var sizeText = $(this).html();$(.sizeText).html(sizeText);});
  4. OMGÂ
  5. ŃFTERvar$sizeHeader = $(#sizeHeader),$sizeText = $(.sizeText),$sizesUl = $(#sizesUl),$sizesUlLi = $sizesUl.find(li),$sizesUlLiSpan = $sizesUlLi.find(span),sizeHeaderWidth = $sizeHeader.width(),sizeHeaderOuterWidth = $sizeHeader.outerWidth(),sizeTextWidth = $sizeText.width();$sizeHeader.width(sizeHeaderWidth);$sizesUl.add($sizesUlLi).width(sizeHeaderOuterWidth);$sizeText.add($sizesUlLiSpan).width(sizeTextWidth);$sizeHeader.on(click,function(){$sizesUl.slideToggle();});$sizesUlLiSpan.on(click, function(){$sizeText.html($(this).html());$sizesUlLi.removeClass(hidden);$(this).parent().addClass(hidden);});
  6. Dont be a fish. Be a shark.
  7. // VAR CACHINGfirst = $(#first);second = $(#second);// USE A CODING CONVENTION (HUNGARIAN NOTATION)var $first = $(#first);var $second = $(#second),var value = $first.val();
  8. // SINGLE VAR PATTERN (putting at the end unassigned vars)var$first = $(#first),$second = $(#second),value = $first.val(),k = 3,cookiestring = IMUSTUSEPROMOTIONEQUALSTRUEBECAUSETHEYWONTFIXAPI,i,j,myArray = {};
  9. // DONT USE DEPRECATED METHODS$first.on(click,function(){$first.css(border,1px solid red);$first.css(color,blue);});// CONDENS JAVASCRIPT$first.on(click,function(){$first.css({border:1px solid red,color:blue});});
  10. // USE CHAINING$second.html(value);$second.on(click,function(){alert(hello everybody);}).fadeIn(slow).animate({height:120px},500);// KEEP THE CODE READABLE$second.html(value);$second.on(click,function(){ alert(hello everybody);}).fadeIn(slow).animate({height:120px},500);
  11. SHORTCIRCUITING// badfunction initVar($myVar) {if(!$myVar) {$myVar = $(#selector);}}// betterfunction initVar($myVar) {$myVar = $myVar || $(#selector);}
  12. SHORTCUTS// badif(collection.length > 0){..}// betterif(collection.length){..}
  13. DETŃCHĒELEMENTSĒWHENĒDOINGĒMŃNIPULŃTIONS// badvar$container = $("#container"),$containerLi = $("#container li"),$element = null;$element = $containerLi.first();// ... do a lot of complicated things// bettervar$container = $("#container"),$containerLi = $container.find("li"),$element = null;$element = $containerLi.first().detach();// ... do a lot of complicated things$container.append($element);
  14. DŃTŃĒŃTTRIBUTES// bad$(#id).data(key,value);// better (faster)$.data(#id,key,value);
  15. BEĒSMŃRT// badvar$sizesUl = $(#sizesUl),$sizesUlLi = $(#sizesUl li),$sizesUlLiSpan = $(#sizesUl li span);// better (faster)var$sizesUl = $(#sizesUl),$sizesUlLi = $sizesUl.find(li),$sizesUlLiSpan = $sizesUlLi.find(span);
  16. Lets talk now about global pollution.
  17. GOLDENĒRULESDont introduce global variables.Dont introduce global functions (unless necessary).Make sure your code doesnt break the outside code.
  18. Global vars.Global functions.Global pollution.WTF global means?
  19. MEŃNSĒTHISfunction original() {console.log(original);}function fake() {original = function() { console.log(fake); }}$(document).ready(function(){original(); // logs originalfake(); // overrides originaloriginal(); // logs fake});
  20. FIRSTĀJSSECONDĀJSfunction hello() {console.log("first");}$(document).ready(function(){hello();});function hello() {console.log("second");}$(document).ready(function(){hello();});
  21. OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><script src="js/second.js"></script><script src="js/lib.jquery.js"></script><script src="js/second.js"></script><script src="js/first.js"></script>
  22. WHŃTBSĒTHEĒDIFFERENCEĒBETWEENÅfish = "nemo";var fish = "nemo";
  23. EXŃMPLEĀJSvar fish = "nemo"; // global$(document).ready(function(){console.log("I am rrready.");});$(document).ready(function(){console.log("I am rrready.");var fish = "nemo"; // local});
  24. Everything is attached to the global object. In the case ofthe web browser, that is the window object. In JavaScript,functions and variables are attributes of the globalobject, which we typically refer to as properties.
  25. FIRSTĀJSSECONDĀJSvar hello = function() {console.log("first");}$(document).ready(function(){hello();});var hello = function() {console.log("second");}$(document).ready(function(){hello();});
  26. OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><script src="js/second.js"></script><script src="js/lib.jquery.js"></script><script src="js/second.js"></script><script src="js/first.js"></script>
  27. SŃMEĒOUTPUTĒŃSĒBEFOREHOLY FISH!
  28. FIRSTĀJSSECONDĀJS$(document).ready(function(){var hello = function() { console.log("first"); }hello();});$(document).ready(function(){var hello = function() { console.log("second"); }hello();});
  29. OURĒWEBPŃGE> first, second> second, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><script src="js/second.js"></script><script src="js/lib.jquery.js"></script><script src="js/second.js"></script><script src="js/first.js"></script>
  30. ŃŃŃŃHĀFinally.
  31. One useful technique to ensure that your variables andfunctions are self contained is to use an IIFE.
  32. // IIFE: immediately invoked func expression(function(){// still mantain access to globals//private membersreturn{//public members}})();
  33. (function(){// vars declarationvar doStuff = function(args) {// some code}return{doThings: function(arga,argb,argc) {..},otherFunction: function(args) {var output = doStuff(args);// other code}}})();
  34. It keeps code to a minimum.It provides a closure which prevents naming conflicts.It’s good for encapsulation.It’s good for garbage collection.
  35. So...What about this?
  36. FIRSTĀJS(function(){var init = function(){console.log(first);};if (typeof $M === undefined) {$M = {};}$M.module = init;})();$(document).ready(function(){$M.module();});
  37. SECONDĀJS(function(){var init = function(){console.log(second);};if (typeof $M === undefined) {$M = {};}$M.module = init;})();$(document).ready(function(){$M.module();});
  38. OURĒWEBPŃGE> second, second> first, first<script src="js/lib.jquery.js"></script><script src="js/first.js"></script><script src="js/second.js"></script><script src="js/lib.jquery.js"></script><script src="js/second.js"></script><script src="js/first.js"></script>
  39. OMGÂÂĒSTILLĒYOUÂÅYes, same namespace.
  40. ŃĒQUICKĒRECŃP
  41. // GLOBALSfunction doThings() { console.log("do things"); }var things = "things";$(document).ready(function(){// LOCALSfunction doStuff() { console.log("do stuff"); }var stuff = "stuff";});
  42. So, again...What about this?
  43. (function () {things = "things";function doThings() { console.log("do things"); }})();$(document).ready(function(){console.log("loaded");});
  44. PLEŃSEAlways put var before any declaration.
  45. HOISTINGundefined != not defined
  46. $(document).ready(function () {console.log($el); // undefined (declared but unassigned)console.log($some) // reference error (not defined)if(Navigation.SUBSECTION == "index"){var $el = $(#element);}if (Navigation.SUBSECTION == "orders") {var $node = $(#node);}});
  47. $(document).ready(function () {var $el, $node; // declarationif(Navigation.SUBSECTION == "index"){$el = $(#element); // assignment}if (Navigation.SUBSECTION == "orders") {$node = $(#node); // assignment}});
  48. Functions are affected by hoisting too.But that is another story...
  49. Questions?Ask Google :)
  50. THŃNKĒYOUĀPlease, dont be an . Ask me before reusing these slides.Matteo Carella © 2013ass

×