Javascript in Practice
Javascript in Practice
Server Side
• Examples:
– SpiderMonkey for Apache mod_js
– Rhino for RhionOnRails, Junction
– Jscript for IIS
JAVASCRIPT ENVIRONMENT
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>
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
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
$$(“#header a.external”).collect(
function(a){
return {a.identify():a.href};
}
);
Prototype
PROTOTYPE
new Ajax.Updater('my_div','/my_url',{method:'get'});
new Ajax.PeriodicalUpdater('my_div','/my_url',
{method:'get'}
);
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!';
}
});
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
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 */
//toggle it (appear|fade)
Effect.toggle('myDiv');
SCRIPTACULOUS
/*
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
Example (Template)
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
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