art of javascript

98
Art of JavaScript

Upload: tarek-yehia

Post on 18-Jan-2015

869 views

Category:

Technology


0 download

DESCRIPTION

Basic JavaScript Object Oriented Best Practices Library MVC Performance Debug Documentation Tools

TRANSCRIPT

  • 1. JavaScript is a lightweight programming language to add interactivity to HTML pages.

2. Putdynamic text into an HTML page. React to events Read and write HTML elements Validate input data Detect the visitor's browser Create cookies 3. New in Html 5: Access new HTML Elements and Events. Draw using canvas object Geolocation: get current location position. Offline Storage Post message Multiple Thread Socket Programming Offline web application 4. Embeddedin Html. Scriptscan be provided locally or remotely. 5. Variablescope and declaration. Popup Boxes: alert("sometext") confirm("sometext") prompt("sometext","defaultvalue") 6. Conditionalstatement if, if.. else, switch Loop for loop, while loop try...catch Throw Encapsulateyour code into functions 7. CommonFeatures DOM Selector DOM modification Traversing Dynamic Styles Events 8. Compatibility Items: Elements Attributes Browser version Device/Operating system Detect the visitor's browser var x = "User-agent header sent: " + navigator.userAgent; User-agent header sent: Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.16 9. var el = document.createElement(new_el); element.appendChild(el);document.body.appendChild(el); 10. var fragment = document.createDocumentFragment (); fragment.appendChild(el_1) fragment.appendChild(el_2) fragment.appendChild(el_3) fragment.appendChild(el_4)document.body.appendChild(fragment); 11. var el = document.getElementById(Id);//single element if (document.all || document.getElementById) { ... } val el = document.get ElementsByClassName(el);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(tagName);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(*);//select all tags val el = document.get ElementsByName(el);//select collection of nodes el[0] //get the first element 12. var el = document.querySelector(#Id);//select first element val el = document.querySelector( .el);//select first element val el = document.querySelectorAll( .el);//select collection of nodes 13. Someold: getElementById getElementsByTagNameNot work with object Somenew: getElementsByClassName Firefox 3, Safari 3, Opera 9.6, IE9 Opera doesnt match a second-specied class querySelectorAll In Firefox 3.1, Safari 3.1, Opera 10, IE 8 Safari 3.1 had memory out of bounds problems Safari 3.2 cant match uppercase characters in quirks mode 14. DOM Collectionlinks document.links document.links[0]formsdocument.forms document.forms[0]anchorsdocument.anhors document. anhors[0] 15. element.innerHTML = HTML code; var attributeValue = element.getAttribute(attributeName); element.setAttribute(attributeName, attributeValue); 16. element.removeChild(el1); 17. var el = element.parentNode; var el = element.childNodes; //Elements + White space var el = element.children; //Only Elements var el = element..nextSibling; //next node or null var el = element..previousSibling; //previous node or null var el = element..nextElementSibling; var el = element..previousElementSibling; 18. onabort- Loading of an image is interrupted onblur - An element loses focus onchange - The content of a field changes onclick - Mouse clicks an object ondblclick - Mouse double-clicks an object onerror - An error occurs when loading a document or an image onfocus - An element gets focus onkeydown - A keyboard key is pressed 19. onkeypress- A keyboard key is pressed orheld down onkeyup - A keyboard key is released onload - A page or an image is finished loading onmousedown - A mouse button is pressed onmousemove - The mouse is moved onmouseout - The mouse is moved off an element onmouseover - The mouse is moved over an element onmouseup - A mouse button is released 20. onreset- The reset button is clicked onresize A window or frame is resized onselect - Text is selected onsubmit - The submit button is clicked onunload - The user exits the page 21. 22. // Internet Explorer element.attachEvent('click', function() { alert(window.event); } ) // Everyone else element.addEventListener('click', function(ev) { alert(ev) }, false ); 23. Bubbling: the event is first captured and handled by the inner most element and then propagated to outer elements. Capturing : event is first captured by the outer most element and propagated to the inner most element. Only event bubbling model is supported by all the major browsers.if ( ) { // W3C DOM Event Model // Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9 } else if ( ) { // Previous IE Event Model code } 24. To preventing any parent event handlers from being executed.addEvent(div, 'mouseover', function(ev) {event = event || window.event // cross-browser event if (event.stopPropagation) { // W3C standard variant event.stopPropagation() } else { // IE variant event.cancelBubble = true } }); 25. JavaScript is an Object Oriented Programming (OOP) language 26. PrimitiveTypes Reference Types 27. Boolean true, false Number 1, 3.141, -1.602e-19 String "Joe" null null undefined undefined 28. Onlyone number type 64 bit floating point Does not map well to common understanding of arithmetic 0.1 + 0.2 = 0.30000000000000004 29. Specialnumber: Not a Number Result of undefined or erroneous operations. Toxic: any arithmetic operation with NaN will have a NaN as a result. NaN is not equal anything including NaN 30. Number(value) Convert the value into a number. It produces NaN if it has a problem. 31. parseInt(value,10) Convert the value into a number. It stops at the first non-digit character. The radix (10) should be required parseInt(08) === 0 parseInt(08, 10) === 8 32. abs absolute value floor integer log logarithm max maximum pow raise to a power random random number round nearest integer sin sin sqrt square root 33. Unicode Stringliterals can use single or double quotes. 34. charAt concat indexOf lastIndexOf match replace search slice split substring toLowerCase toUpperCase 35. Avalue that isnt anything 36. Defaultvalue for variables and parameters The value of missing members in objects function isDefined(value) { return(typeof value != "undefined"); } 37. Date new Date(1211623944453); Error new Error("Oops!"); RegExp /^web.*$/i; Array [ "apple", "banana" ] Function function(x) {return x*x} 38. Date new Date() ; //Current date new Date(year, month, day); Date.parse('2/6/2009');//wrong will depend on culture Y2KProblemDate.prototype.getRealYear = function() { if(this.getFullYear) return this.getFullYear(); else return this.getYear() + 1900; }; 39. unordered collection of properties with arbitrary values object literal var obj = { name: "Joe", age: 26 }; setting a property obj.lastName = "Smith"; retrieving properties alert(obj.name + " " + obj.lastName); 40. Data structure that associates arbitrary values with arbitrary strings property name as an identifier obj.lastName = "Smith"; property name as a string obj["lastName"] = "Smith"; for( prop in obj ) { alert( prop + ": " + obj[prop] ); } 41. Concept of a class does not exist... ... but use a function as a constructor: function Dog() {}; class Dog var lassie = new Dog(); instance lassie alert(lassie instanceof Dog); // true 42. Because functions are first-class objects we can attach properties: Class Variables Dog.SPECIES = "Canis lupus"; Class Methods Dog.getCount = function() { return Dog.COUNT; }; 43. InstanceVariables function Dog(name) { this.name = name; }; var lassie = new Dog("Lassie"); alert( lassie.name ); 44. InstanceMethods function Dog(name) { this.name = name; this.bark = function() { alert("Woof!") }; }; var lassie = new Dog("Lassie"); lassie.bark(); 45. GlobalScope Variables outside of any functions Variables inside functions without varvar global1 = 1; global2 = 2; function foo() { global3 = 3; }; 46. FunctionScope Variables inside functions declared with var Function arguments function foo(local1) { var local2 = 2; }; 47. BlockScope ... but can be faked: // before block (function() { // inside block })(); // after block 48. function Dog(name) { var _name = name; // private variable // privileged method this.getName = function() { return _name; }; }; var lassie = new Dog("Lassie"); alert( lassie.getName() ); 49. function Dog(name) { var _name = name; // private method var _fixName = function() { return _name.toUpperCase(); }; this.getName = function(){ return _fixName(); }; }; 50. Nestedfunctions Inner function has still access to local variables even after the outer function has finished 51. function outer() { var count = 1; function inner() { alert(count++) } return inner; } var myClosure = outer(); myClosure(); // ==> 1 myClosure(); // ==> 2 52. functionPet() {}; Pet functionDog() {}; Dog.prototype= new Pet; Dog 53. function Pet(name) { this.name = name; }; function Dog(name) { // super(name) Pet.call( this, name ); this.bark = function() {}; }; Dog.prototype = new Pet; 54. //old: attach to "thisfunction Dog(name) { this.bark = function(){ alert("Woof!") }; }; //new: attach to "prototype"function Dog(name) {}; Dog.prototype.bark = function(){ alert("Woof!") }; }; 55. Propertyvalues on instance: local, instance-specific values Property values on prototype: read-only default values attaching to the prototype saves memory, especially for large numbers of instances 56. Affectsall new instances Affects all existing instances Allows modification of existing classes String.prototype.trim = function() { return this.replace(/^s+/, ""); }; alert(" Lassie".trim() ); 57. function Dog() {}; Dog.prototype.bark = function() { alert("Woof!") }; function Bulldog() {}; Bulldog.prototype = new Dog; Bulldog.prototype.bark = function() { // super.bark(); Dog.prototype.bark.call(this); alert("Grrrh!!") }; 58. function Pet() { if(this._id == Pet._id) { throw new Error("No Pets, please!"); } } Pet._id = "Pet"; Pet.prototype._id = "Pet"; var fiffy = new Pet; // Error (intended) 59. But now our code to setup inheritance will fail: Dog.prototype = new Pet; // Error :-( Solution: Do not create an instance of the actual superclass just to setup inheritance, use a dummy: function Dummy() {}; Dummy.prototype = Pet.prototype; Dog.prototype = new Dummy; 60. if (typeof very == "undefined") { very = {}; } if (typeof very.cute == "undefined") { very.cute = {}; } very.cute.Dog = function() {}; var fiffy = new very.cute.Dog; 61. // The Last of the Mohicans var chingachgook = { fight : function() { alert("Woah!"); } }; chingachgook.fight(); 62. function Mohican() { this.fight = function(){alert("Woah!")} }; Mohican.getInstance = function() { if (!this._instance) { this.instance = new this; } return this._instance; }; Mohican.getInstance().fight(); 63. Avoiding Conflicts with Other Libraries ($) 64. use multiple window.onload events with external scripts:window.onload = init; function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) {var oldOnload = window.onload; window.onload = function ( e ) {oldOnload( e ); window[fnc]();}; } else window.onload = fnc; } } addOnloadEvent(myFunctionName); 65. Feature-Detect Rather Than Browser-Detectif (document.getElementById) { var element = document.getElementById('MyId'); } else { alert('Your browser lacks the capabilities required to run this script!'); } Use Square Bracket Notation MyObject.property MyObject."value"+I(Work) (not Work)formref.elements.name[] (not Work)MyObject["property"] (Work) MyObject["value"+i] (Work)formref.elements["name[]"] (Work) 66. Use onclick In Anchors Instead Of javascript: Pseudo-Protocol Home function validate() { return prompt("Are you sure you want to exit this page?"); }What Not To Do link link link link 67. Use The Unary + Operator To TypeConvert To Numberfunction total() { var theform = document.forms["myform"]; var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value); alert(total); // This will alert 3 } Don't Use HTML Comments In Script Blocks 68. Avoid Cluttering The Global Namespacevar MyLib = {}; // global Object cointainer MyLib.value = 1; MyLib.increment = function() { MyLib.value++; } MyLib.show = function() { alert(MyLib.value); } MyLib.value=6; MyLib.increment(); MyLib.show(); // alerts 7 69. Model: organize the application's data layer. View: Templates to render HTML data in controllers and inject them into the DOM. Composed Views: divide the view into small blocks which can be reused or adapted to different scenarios. Controller : A controller is a list of functions that gets called back when the appropriate event happens. 70. ExtendMethods. UI Controls and Library. Compatibility. Performance. 71. Jquery TheDojo Toolkit The Yahoo! User Interface Library Prototype (and Script.aculo.us) MooTools ExtJS provides everything you need to build robust desktop and mobile web apps. 72. JavaScriptMVC Knockout AngularJS 73. FrameworkUI BindingsComposed ViewsWeb Presentation LayerPlays Nicely With OthersBackbone.jsSproutCore 1.xSammy.jsSpine.jsCappuccinoKnockout.jsJavascript MVCGoogle Web ToolkitGoogle ClosureEmber.jsAngular.jsBatman.js 74. Define local variables var doc = document; elem = doc.getElementById(objId); Combine control conditions and control variable changes when using loops var x = 9; do { } while( x-- ); 75. Define arrays for HTML collection objectsfunction array(items) { try { return Array.prototype.concat.call(items); } catch (ex) { var i = 0, len = items.length, result = Array(len); while (i < len) { result[i] = items[i];i++; } return result; } } var divs = array( document.getElementsByTagName('div') ); for (var i=0l i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); } 76. Appending DOM elements all at once faster than adding them individually. var div = document.getElementsByTagName("div"); var fragment = document.createDocumentFragment(); for ( var e = 0; e < elems.length; e++ ) { fragment.appendChild( elems[e] ); }for ( var i = 0; i < div.length; i++ ) { div[i].appendChild( fragment.cloneNode(true) ); } Change CSS classes not styles 77. Optimizing Events

  • Home
  • Products
  • Portfolio
  • Shop

var menuHandler = function(event) { event = event || window.event; var target = event.target || event.srcElement; if (target.id === 'home') {// go home} } document.getElementById('menu').addEventListener('cli ck',menuHandler); 78. Avoid memory leaks and circular references in your closures//Classic case for circular references function foo(e,d) { $(e).on("click", function() { //Do something with d }); } //Break the cycle! function foo(e, d) { $(e).on("click", cbk(d)); } function cbk (d) { } Avoid using eval Minimize file size Caching use external file Deferred execution 79. Loading on demand Minimize file size (use minified files) Deferred execution 80. Frame Eval HtmlEncode: escape encodeURI encodeURIComponent html.replace(/,"") Obfuscateusing tool YUI Compressor. Will it protect javascript? 81. TOOLS 82. Firebug (FF) MS Visual Web Developer (IE) DragonFly (Opera) Chrome Drosera / Web Inspector (Safari) Console:http://code.google.com/p/console-js/ http://patik.com/blog/complete-cross-browserconsole-log/ 83. DojoShrink Safe http://shrinksafe.dojotoolkit.org/ YUI http://refresh-sf.com/yui/ Dean Edwards Packer / Compress.js 84. Yslow Firebug Chrome'sdevelopment tools 85. Inbrowser (easy) - JSUnit Browser Control (comprehensive) Selenium http://www.seleniumhq.org/ Simulated (fast) Env.js http://www.envjs.com/ 86. Understands JavaScript, hard to document complex features http://code.google.com/p/jsdoc-toolkit/ Natural Docs Can document anything MVCDoc Can document anything, understands some JS. JSDoc