SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
1.
5 tips for writing better
JavaScript
Nael El Shawwa
@naelshawwa
nael.elshawwa@gmail.com
http://about.me/naelshawwa
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.
Tip # 1: Namespacing
function hello(){ var nael = {};
alert (“Hello”);
} nael.hello = function(){
alert (“Hello”);
};
Stop declaring global functions, minimize
global variables
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.
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.
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.
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.
How to learn more?
http://www.crockford.com/ - Douglas
Crockford
High Performance JavaScript - Nicholas
Zakas
Use & read into jQuery, Dojo, YUI code bases