Successfully reported this slideshow.

5 Tips for Writing Better JavaScript

3

Share

Upcoming SlideShare
Application Events
Application Events
Loading in …3
×
1 of 8
1 of 8

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

Related Audiobooks

Free with a 14 day trial from Scribd

See all

5 Tips for Writing Better JavaScript

  1. 1. 5 tips for writing better JavaScript Nael El Shawwa @naelshawwa nael.elshawwa@gmail.com http://about.me/naelshawwa
  2. 2. Why learn better JS? Easy to hack things Easy to learn bad habits Rich web apps today heavily depend on JS 20,000 lines of JS
  3. 3. Tip # 1: Namespacing function hello(){ var nael = {}; alert (“Hello”); } nael.hello = function(){ alert (“Hello”); }; Stop declaring global functions, minimize global variables
  4. 4. Tip # 2: Events <a onclick=”doSomething();”> dojo.connect(link, "onclick", ui, Do Something ui.doSomething); </a> Don’t bind behaviour using markup attributes remember no global functions? harder to change behavior in a large app
  5. 5. Tip # 3: Pub Sub startup: function(){ //some other startup code //subscribe to the event we will get back from the app dojo.subscribe("nael.controller.app.currentPosition", this, this.eventHandlers.updateMapCenter); //when Im done starting up, yell to the app controller saying Im ready dojo.publish("nael.controller.app.requests", ["getBrowserCoordinates"]); }, Publish / Subscribe results in cleaner more maintainable code
  6. 6. Tip # 4: Templating <div class="infoWindowContainer" dojoattachpoint="infoWindow"> <h1>${title}</h1> </div> Don’t mix HTML with JavaScript Keep your markup in HTML and load via ajax ex. Dojo widget template system
  7. 7. Tip # 5: Decorating var car = {}; car.drive = function(x){ this.position = this.position + x; } var flyingDecorator = {}; flyingDecorator.fly = function(x,y){ this.position = this.position + x; this.height = this.height + y; } Combine objects together when needed, don’t copy and paste new code into existing objects
  8. 8. How to learn more? http://www.crockford.com/ - Douglas Crockford High Performance JavaScript - Nicholas Zakas Use & read into jQuery, Dojo, YUI code bases

Editor's Notes

  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • ×