You are on page 1of 48

JAVASCRIPT IN PRACTICE

Real World Usage Examples


Javascript Environment
JAVASCRIPT ENVIRONMENT

Client Side, The Browser


• JavaScript is mostly used inside a browser
environment.
• Several implementations exist for different browser
engines:
– SpiderMonkey for Gecko (FireFox)
– Futhark for Presto (Opera)
– KJS for KHTML (Konqueror)
– JavaScriptCore for WebCore (Safari)
– JScript for Trident (Internet Explorer)
JAVASCRIPT ENVIRONMENT

Server Side
• Examples:
– SpiderMonkey for Apache mod_js
– Rhino for RhionOnRails, Junction
– Jscript for IIS
JAVASCRIPT ENVIRONMENT

Forget The Server For Now

We Will Focus On The Browser


JAVASCRIPT ENVIRONMENT

What does the browser provide?


• The Javascript interpreter
• A sand box for secure execution of JavaScript
• An Interface to the HTML DOM
Document Object Model
DOCUMENT OBJECT MODEL

DOM? What DOM?


• The Document Object Model is an API for HTML and
XML documents
• It exposes all the different components of the
documents as objects
• You can manipulate those objects in Javascript using
the provided APIs
• It also provides event notification
• The interface is standardized as the “W3C DOM” by
the World Wide Web Consortium
DOCUMENT OBJECT MODEL

Sample DOM
DOCUMENT OBJECT MODEL

Examples
<p>Parapgraph1</p>
<p>Parapgraph2</p>
<p>Parapgraph3</p>
<div id=”myBlock”>It's my property!</div>
<div id=”notMyBlock”>I wish to own it!</div>

var paragraphs = document.getElementsByTagName("P");


// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);

var myBlock = document.getElementById("myBlock");


// myBlcok is <div id=”myBlock”></div>
alert(myBlock.tagName);
DOCUMENT OBJECT MODEL

Important Objects and Interfaces


• The “window” object
• The “document” object
• The “node” interface
• The “element” interface
window.location.href //using the window object
x = document.getElementById(“x”) //the document object
x.parentNode //the node interface
x.tagName //the object itself
x.innerHTML //the element interface
DOCUMENT OBJECT MODEL

Compatibility Issues
• Most cross browser compatibility issues stem from the
differences in DOM implementations
• JS engines themselves are fairly compatible
• Differences lead to ugly code
var x = document.getElementById(“x”);
var index = null;
if (document.all) { //bad browser detection
index = x.sourceIndex
} else {
var elements = document.getElementsByTagName(“*”);
for (var elIndex in elements){
if(elements[elIndex] == x)index = elIndex;
}
}
DOCUMENT OBJECT MODEL

The Ultimate Reference


in Cross Browser DOM
Compatibility Issues

Peter-Paul Koch,
Author of quirksmode.org
DOCUMENT OBJECT MODEL

DOM Issues
• Incompatible implementations (becoming less of an
issue)
• Lacking API (a bit too simplistic, a bit too verbose)
• All is not lost! We can stand on the shoulders of giants!
MAJOR JAVASCRIPT LIBRARIES
MAJOR JAVASCRIPT LIBRARIES

Different Targets
• Prototype, JQuery and Mochikit focus on extending
Javascript and DOM objects
• EXTJS and Dojo are more geared towards interface
toolkits
• Scriptaculous and MooTools focuse more on DOM
effects
• TrimPath is a development toolkit with a query
language, a templating language and a complete
application framework
MAJOR JAVASCRIPT LIBRARIES

DOM in Prototype
• Prototype provides add ons to DOM elements that has
the following benefits:
– Enrich the standard interfaces with more methods
– Handle browser incompatibilities at the core
– Implement much more versatile DOM accessors
//example new DOM methods
var x = $(“x”); //similar to document.getElementById
var y = x.previous();
var yId = y.identify();
y.remove();
//retrieve a list of DOM elements using a CSS selector
var longParagraphs = $$(“#main P.long”)
CSS SELECTORS

Whar are CSS selecotrs?


• The CSS way of finding elements to apply styles on
them
• Prototype implements the whole CSS3 selectors in a
cross browser fashion
• You can select elements based on:
– Tag name (P, A, DIV)
– CSS class (.active, .very-active)
– Element id (#order-1, #returnDiv)
– Any Attribute (a[rel], a[href='#'])
– Special psuedo-selectors (a:hover, li:first-child)
– Any of the above combined (A#link-1.active:hover)
CSS SELECTORS IN PROTOTYPE

Provided via the $$() global method


It takes a string with the CSS selector value and returns
an array of matching elements
Examples:
/* return a list of paragraphs that have the class long
and descend from the element with id 'main' */
$$(“#main p.long”)

/* return the list items that are first childs of lists


with the active class belonging to an element with id
'header' */
$$(“#header ul.active li:first-child”)

/* loop an all input fields whose enabled property is


not equal to false and set it to false */
$$(“input[enabled!=false]”).each(function(input){
input.enabled = false;
})
CSS SELECTORS IN PROTOTYPE

Very Powerful In Combination With Iterators


Examples:

$$(“div#main p.long ul li:first-child”).invoke('hide');

$$(“div#main p.long ul li:first-child”).each(


function(li){
li.hide();
}
);

$$(“#header a.external”).collect(
function(a){
return {a.identify():a.href};
}
);
Prototype
PROTOTYPE

Prototype comes with more goodies


• Various utility methods (like $() and $$())
• Powerful Ajax implementation
• Class based OOP (for the classical among us)
• JSON support for all Javascript objects
• Various enumerators (in the Enumerable module)
• Event handling
• Form Serialization
• And more ..
Prototype['Ajax']
PROTOTYPE

Ajax Support In Prototype


• What is Ajax?
– Asynchronus Javascript and XML
– Basically you can send requests and get a response
without leaving your current page
• Prototype make Ajax easy
new Ajax.Request('/my_url',
{method:'post',parameters:form.serialize()}
);

new Ajax.Updater('my_div','/my_url',{method:'get'});

new Ajax.PeriodicalUpdater('my_div','/my_url',
{method:'get'}
);
PROTOTYPE

Advanced Ajax Features


• Callbacks for
– Create
– Complete
– Success
– Failure
– Exception
new Ajax.Request('/some_url',
{method:'get',onSuccess: function(transport){
var response =
transport.responseText || "no response text";
},
onFailure: function(){
alert('Something went wrong...') }
});
PROTOTYPE

Advanced Ajax Features


• Global responders for all Ajax requests
• Ajax.Responders registers callbacks for all requests
• Very useful for global operations like displaying a
“loading..” message
Ajax.Responders.register({
onCreate: function(){
alert('a request has been initialized!');
},
onComplete: function(){
alert('a request completed');
}
});
/* every Ajax request will trigger the onCreate and
onComplete callback functions */
Prototype['Class']
PROTOTYPE

Class Based Inheritance


• Prototype provides a classical class based inheritance
model
• It implements various class based features:
– Super method calling
– Mixins (mixed in modules)
– Initialization (constructor) methods
• It is implemented internally via prototypal inheritance
PROTOTYPE

Example
// properties are directly passed to `create` method
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
});
// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
say: function($super, message) {
return $super(message) + ', yarr!';
}
});

var john = new Pirate('Long John');


john.say('ahoy matey');// -> "Long John: ahoy matey, yarr!"
PROTOTYPE

Modules (Mixins)
• Modules are normal Javascript Objects (POJOs)
• All methods defined in a module can be mixed-in
during class declaration
• Or later via the addMethods() method
PROTOTYPE

Example
// define a module
var Vulnerable = {
wound: function(hp) {
this.health -= hp;
if (this.health < 0) this.kill();
},
kill: function() { this.dead = true;}
};
/* the first argument isn't a class object, so there is no
inheritance ... simply mix in all the arguments as methods: */
var Person = Class.create(Vulnerable, {
initialize: function() {
this.health = 100;
this.dead = false;
}
});
var bruce = new Person;
bruce.wound(55);
bruce.health; //-> 45
PROTOTYPE

Example (mixing a module after class definition)

var john = new Pirate('Long John');


john.sleep();
// -> ERROR: sleep is not a method

// every person should be able to sleep, not just pirates!


Person.addMethods({
sleep: function() {
return this.say('ZzZ');
}
});

john.sleep();
// -> "Long John: ZzZ, yarr!"
Prototype['Event']
PROTOTYPE

Events
• Prototype provides a cross browser event library
• Very simple yet powerful API

$('foo').observe('click', respondToClick);

function respondToClick(event) {
var element = event.element();
element.addClassName('active');
}

$('foo').observe('click', function(event) {
var element = event.element();
element.addClassName('active');
});
Prototype['JSON']
PROTOTYPE

JSON
• JavaScript Object Notation
• Prototype implements Crockford's JSON methods
• Methods are added to basic objects' prototypes
{
method :
{
name : 'add',
type : 'float',
argumnets :
[
{name: 'a', type:'float'},
{name:'b', type:'float'}
]
}
}
Scriptaculous
SCRIPTACULOUS

Scriptaculous
• Add on to Prototype that provides:
– Dynamic HTML effects
– Several UI controls
– Drag 'n' Drop, Sortables support
• Very easy to use and extend
/* combinational effects */

//fade my div away


Effect.Fade('myDiv');

//make it appear in 3 seconds


Effect.Appear('myDiv',{duration:3.0});

//toggle it (appear|fade)
Effect.toggle('myDiv');
SCRIPTACULOUS

Sortables example (uses Drag 'n' Drop)

<!-- a normal list of items with the id 'listA' -->


<ul id=”listA”>
<li>item1</i>
<li>item2</i>
<li>item3</i>
<li>item4</i>
<li>item5</i>
<li>item6</i>
</ul>

/*
Calling Sortable.create with the id of the list
will cause all the items of the list to be
draggables and the list itself will act as a drop
container to the items. Users can sort the items
at will this way
*/
Sortable.create('listA');
TrimPath
TRIMPATH

JavaScript Templates (JST)


• Allows templates like php, jsp, asp or RHTML
• It looks a lot like Smarty (PHP) or FreeMarker (Java)
• Provides filters and pipes for chaining them
• Lightweight templating system
• You can introduce your own filters
• Usage pattern:
– Define a template
– Parse it (it gets converted to method calls)
– Process it by providing data (JS object)
– The resulting text go to an element's innerHTML
TRIMPATH

Example (Template)

Hello ${customer.first} ${customer.last}.<br/>


Your shopping cart has ${products.length} item(s):
<table>
<tr>
<th>Name</th><th>Description</th>
<th>Price</th><th>Quantity & Alert</th>
</tr>
{for p in products}
<tr>
<td>${p.name|capitalize}</td>
<td>${p.desc}</td>
<td>${p.price}</td>
<td>${p.quantity}</td>
</tr>
{forelse}
<tr>
<td colspan="4">No products in your cart.
</tr>
{/for}
</table>
TRIMPATH

Example (JavaScript Object)

var data = {
products : [
{
name: "mac", desc: "computer",
price: 1000, quantity: 100
},
{
name: "ipod", desc: "music player",
price: 200, quantity: 200
}
],
customer :
{
first: "John", last: "Public"
}
};
TRIMPATH

Example (Result)
Hello John Public.<br/>
Your shopping cart has 3 item(s):
<table>
<tr>
<td>Name</td><td>Description</td>
<td>Price</td><td>Quantity & Alert</td>
</tr>
<tr>
<td>MAC</td>
<td>computer</td>
<td>$1000</td>
<td>100</td>
</tr>
<tr>
<td>IPOD</td>
<td>music player</td>
<td>$200</td>
<td>200</td>
</tr>
</table>
TRIMPATH

Other TrimPath Libraries


• TrimQuery
– A SQL engine for JavaScript objects
– Allows querying of object arrays with plain old SQL
• TrimJunction
– An MVC framework that is entirely JavaScript
– Heavily ported from Ruby on Rails
– Uses JST (or EST) for view layer
– Uses TrimQuery and/or GoogleGears for models
– Provide a controller implementation
– Runs both online and offline
– Provides a means of server synchronization
NEW DOM FEATURES
NEW DOM FEATURES

DOM Storage
• Session Storage
– A means of sharing data across a browser session
– All pages must belong to the same domain
• Global Sotrage
– Global data storage that outlives the session
– Can be used across domains and web sites

sessionStorage[ 'name' ] = "oldmoe";

globalStorage[ 'espace.com.eg' ][ 'CTO' ] = “oldmoe”

globalStorage[ '' ][ 'testing' ] = “123”


NEW DOM FEATURES

Canvas HTML Element


• Not particularly new
• Pixel level access (I have been personally looking for
this for a while)
• Vector drawing tools (circle, line, etc)
• Can be used for very novel uses
Thank You
Mohammad A. Ali
CTO, eSpace