Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

5 Tips for Writing Better JavaScript

3,589 views

Published on

Published in: Technology
  • Be the first to comment

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 thingsEasy to learn bad habitsRich web apps today heavily depend on JS 20,000 lines of JS
  3. 3. Tip # 1: Namespacingfunction 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 Substartup: 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 controllersaying 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’tcopy and paste new code into existingobjects
  8. 8. How to learn more?http://www.crockford.com/ - DouglasCrockfordHigh Performance JavaScript - NicholasZakasUse & read into jQuery, Dojo, YUI code bases

×