javascript in practice

48
JAVASCRIPT IN PRACTICE Real World Usage Examples

Upload: oldmoe

Post on 12-Nov-2014

1.601 views

Category:

Documents


0 download

DESCRIPTION

A quick survey in real world javascript usage examples

TRANSCRIPT

Page 1: Javascript in Practice

JAVASCRIPT IN PRACTICEReal World Usage Examples

Page 2: Javascript in Practice

Javascript Environment

Page 3: Javascript in Practice

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)

Page 4: Javascript in Practice

JAVASCRIPT ENVIRONMENT

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

Page 5: Javascript in Practice

Forget The Server For Now

We Will Focus On The Browser

JAVASCRIPT ENVIRONMENT

Page 6: Javascript in Practice

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

Page 7: Javascript in Practice

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

Page 8: Javascript in Practice

DOCUMENT OBJECT MODEL

Sample DOM

Page 9: Javascript in Practice

Examples

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);

<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>

DOCUMENT OBJECT MODEL

Page 10: Javascript in Practice

Important Objects and Interfaces• The “window” object• The “document” object• The “node” interface• The “element” interface

DOCUMENT OBJECT MODEL

window.location.href //using the window objectx = document.getElementById(“x”) //the document objectx.parentNode //the node interfacex.tagName //the object itselfx.innerHTML //the element interface

Page 11: Javascript in Practice

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 codevar 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; }}

Page 12: Javascript in Practice

DOCUMENT OBJECT MODEL

Peter-Paul Koch, Author of quirksmode.org

The Ultimate Reference in Cross Browser DOM Compatibility Issues

Page 13: Javascript in Practice

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!

Page 14: Javascript in Practice

MAJOR JAVASCRIPT LIBRARIES

Page 15: Javascript in Practice

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

Page 16: Javascript in Practice

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 methodsvar 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 selectorvar longParagraphs = $$(“#main P.long”)

Page 17: Javascript in Practice

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)

Page 18: Javascript in Practice

Provided via the $$() global methodIt takes a string with the CSS selector value and returns an array of matching elementsExamples:

CSS SELECTORS IN PROTOTYPE

/* 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;})

Page 19: Javascript in Practice

CSS SELECTORS IN PROTOTYPE

Very Powerful In Combination With IteratorsExamples:

$$(“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};

});

Page 20: Javascript in Practice

Prototype

Page 21: Javascript in Practice

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 ..

Page 22: Javascript in Practice

Prototype['Ajax']

Page 23: Javascript in Practice

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 easynew 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'});

Page 24: Javascript in Practice

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...') } });

Page 25: Javascript in Practice

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

PROTOTYPE

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 */

Page 26: Javascript in Practice

Prototype['Class']

Page 27: Javascript in Practice

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

Page 28: Javascript in Practice

// properties are directly passed to `create` methodvar 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 fromvar 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!"

Example

PROTOTYPE

Page 29: Javascript in Practice

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

Page 30: Javascript in Practice

PROTOTYPE

Example// define a modulevar 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

Page 31: Javascript in Practice

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!"

Page 32: Javascript in Practice

Prototype['Event']

Page 33: Javascript in Practice

PROTOTYPEPROTOTYPE

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');});

Page 34: Javascript in Practice

Prototype['JSON']

Page 35: Javascript in Practice

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'} ]

}}

Page 36: Javascript in Practice

Scriptaculous

Page 37: Javascript in Practice

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 awayEffect.Fade('myDiv');//make it appear in 3 seconds Effect.Appear('myDiv',{duration:3.0});//toggle it (appear|fade)Effect.toggle('myDiv');

Page 38: Javascript in Practice

SCRIPTACULOUS

Sortables example (uses Drag 'n' Drop)

/*Calling Sortable.create with the id of the listwill cause all the items of the list to bedraggables and the list itself will act as a dropcontainer to the items. Users can sort the itemsat will this way

*/Sortable.create('listA');

<!-- 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>

Page 39: Javascript in Practice

TrimPath

Page 40: Javascript in Practice

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

Page 41: Javascript in Practice

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>

Page 42: Javascript in Practice

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

Page 43: Javascript in Practice

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>

Example (Result)

TRIMPATH

Page 44: Javascript in Practice

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

Page 45: Javascript in Practice

NEW DOM FEATURES

Page 46: Javascript in Practice

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”

Page 47: Javascript in Practice

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

Page 48: Javascript in Practice

Thank YouMohammad A. Ali

CTO, eSpace