You are on page 1of 70

JavaScript Libraries Overview
Siarhei Barysiuk
s.barysiuk@sam-solutions.net

Our roadmap

..Libraries: What we will cover today. 5 great open source libraries for your project. • prototype • jQuery • dojo • qooxdoo .

Libraries: General picture Global picture Lightweight Widgets One-page Applications .

Prototype .

org .Prototype: Overview http://prototypejs.

Prototype: Focus • DOM manipulation • Ajax transport • Utility methods for built-in objects • Class-based OOP .

Say hello to $() $("id"). $(element) extended DOM element .getElementById("id").innerHTML = "<li>node</li>".Prototype: DOM manipulation Say goodbye to getElementById() document.innerHTML = "<li>node</li>".

update('I read this message!').addClassName('read').Prototype: DOM Element extension * absolutize * addClassName * addMethods * adjacent * ancestors * childElements * classNames * cleanWhitespace * clonePosition * cumulativeOffset * cumulativeScrollOffset * descendantOf * descendants * down * empty * extend * fire * firstDescendant * getDimensions * getElementsByClassName * getElementsBySelector * getHeight * getOffsetParent * getStyle * getWidth * hasClassName * hide * identify * immediateDescendants * insert * inspect * makeClipping * makePositioned * match * next * nextSiblings * observe * positionedOffset * previous * previousSiblings * readAttribute * recursivelyCollect * relativize * remove * removeClassName * replace * scrollTo * select * setOpacity * setStyle * show * siblings * stopObserving * toggle * toggleClassName * undoClipping * undoPositioned * up * update * viewportOffset * visible * wrap * writeAttribute $('message'). .setStyle({opacity: 0.5}).

a.createTextNode("Next page")). 'foo').Prototype: Creating a DOM element The old way: var a = document. { 'class': 'foo'.html').setAttribute('href'. '/foo. a. The new way: var a = new Element('a'.appendChild(document.html' }). href: '/foo.update("Next page").setAttribute('class'. a.createElement('a'). .

..Prototype: Even more bucks $((id | element).] $$(cssRule..) -> [HTMLElement. exclusive = false]) -> ObjectRange $w(String) -> Array .) -> [HTMLElement.. end[...] $A(iterable) -> actualArray $F(element) -> value $H([obj]) -> Hash $R(start...

element. respondToClick).element().Prototype: Event handling $('foo').observe('click'. } . function respondToClick(event) { var element = event.addClassName('active').

. Also available are onXXX callbacks. alert("Success! \n\n" + response)..{ method:'get'. onSuccess: function(transport){ var response = transport.Prototype: Ajax transport new Ajax.') } }). where XXX is the HTTP response status like 200 or 404.Request('/some_url'.. onFailure: function(){ alert('Something went wrong. }.responseText || "no response text".

Prototype: Ajax transport new Ajax.serialize(true) }).Request('/some_url'. limit: 12} }). { parameters: $('id_of_form_element'). form serialization . parameters: {company: 'example'.Request('/some_url'. { method: 'get'. new Ajax.

1 { method: 'get'.Prototype: Ajax magic new Ajax. 3. 2 insertion: Insertion.2 4 .Top } ).1 failure: 'errors' }. 3. '/some_url'.Updater( { success: 'products'.

'bar'. }. baz: 2} * all * any * collect * detect * each * eachSlice * entries * find * findAll * grep * inGroupsOf * include * inject * invoke * map * max * member * min * partition * pluck * reject * select * size * sortBy * toArray * zip . bar: 1.Prototype: Built-in object extensions var myObject = {}. 'baz']. myObject). ['foo'. index) { this[name] = index.each(function(name. // we have specified the context myObject //-> { foo: 0.

Prototype: Built-in object extensions
"<h1>hello, i'm HTML</h1>".escapeHTML()
//-> "&lt;h1&gt;hello, i'm HTML&lt;/h1&gt;"
'background-color'.camelize(); // -> 'backgroundColor'
'Prototype framework'.include('frame'); //-> true
'Prototype framework'.include('frameset');//-> false
"echo ".times(3);

//-> "echo echo echo "

"#{animals} on a #{transport}".interpolate({
animals: "Pigs",
transport: "Surfboard" });
//-> "Pigs on a Surfboard"

* blank
* camelize
* capitalize
* dasherize
* empty
* endsWith
* escapeHTML
* evalJSON
* evalScripts
* extractScripts
* gsub
* include
* inspect
* interpolate
* isJSON
* parseQuery
* scan
* startsWith
* strip
* stripScripts
* stripTags
* sub
* succ
* times
* toArray
* toJSON
* toQueryParams
* truncate
* underscore
* unescapeHTML
* unfilterJSON

Prototype: Class-based OOP
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
});

var Pirate = Class.create(Person, {
// redefine the speak method
say: function($super, message) {
return $super(message) + ', yarr!';
}
});
var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

Prototype: Real life example
http://gmx.com http://web.de http://gmx.de

us • good documented • a lot of real project which use prototype .aculo.Prototype: Conclusion • lightweight • good for small projects • a lot of useful methods • transport support • effects with script.

Questions? .

jQuery .

com .jQuery: Overview http://jquery.

jQuery: Focus Motto: Write less. • DOM manipulation • Ajax transport • Effects • Other functionality with plugins . do more.

$("div").span.css("border"."3px solid red").css("border". $(". $("*").myClass"). ."3px solid red").css("border".p.css("border".jQuery: DOM manipulation Very powerful selectors."3px solid red")."3px solid red").myClass"). $("div. $("#myDiv").css("border"."3px solid red").

li.jQuery: DOM manipulation Even more powerful than you expect.goofy)') $('p a[href*=#]') $('code.goofy') $('ol .goofy > strong') $('li + li > a[href$=pdf]') $('span:hidden') . $('li:eq(0)') $('li:even') $('li:lt(3)') $('li:not(.

jQuery: DOM manipulation Attributes: attr( name ) attr( properties attr( key. value removeAttr( name Text: ) ) ) ) Classes: addClass( class ) hasClass( class ) removeClass( class ) toggleClass( class ) text( ) text( val ) HTML: html( ) html( val ) Value: val( ) val( val ) . value attr( key.

jQuery: DOM manipulation append( content ) appendTo( content ) prepend( content ) prependTo( content ) after( content ) before( content ) insertAfter( content ) insertBefore( content ) wrap( html ) replaceWith( content ) clone( ) .

data ) . 3 main methods: bind( type. fn ) trigger( type. data. data ) unbind( type.jQuery: Events Very convenient event handling system.

function(e){ var str = "( " + e. . function(){ $("span"). }).bind("mouseenter mouseleave".tagName).trigger("click").bind("click". $("p"). }). }). " + e.toggleClass("over"). $("p"). $("span").jQuery: Binding event handlers $("p").text("Double-click happened in " + this.pageY + " )". $("p").text("Click happened! " + str).pageX + ".bind("dblclick". function(e){ $(this).

$("p").jQuery: Binding event handlers $("p").text("Double-click happened in " + this.tagName).pageX + ".dblclick(function(){ $("span"). $("span"). }). . }).pageY + " )".text("Click happened! " + str).click(function(e){ var str = "( " + e.click(). " + e. $("p").

fadeOut(1000).stop(). }). myValue){ $(this). . $("button"). myName. hi there!").css("opacity".text("myName = " + myName) . [ "John" ]). 1) .trigger("myCustomEvent".text(myName + ".click(function () { $("p").fadeIn(30).bind("myCustomEvent". $("span"). function(e.jQuery: Custom events $("p"). }).

.ready(function () { $("p").").jQuery: onload event $(document). }).text("The DOM is now loaded and can be manipulated.

success: function(msg){ alert( "Data Saved: " + msg ).ajax({ url: "test.ajax({ type: "POST". } }). cache: false. data: "name=John&location=Boston".php". .html". } }). $.jQuery: Ajax transport $.append(html). url: "some. success: function(html){ $("#results").

jsonp:"jsoncallback". dataType:"jsonp". success: function(data){ //.jQuery: Ajax transport $.. }) } }) .gne? tags=cat&tagmode=any&format=json".flickr.ajax({ url:"http://api.com/services/feeds/photos_public..

jQuery: Effects show/hide toggle slideDown/slideUp slideToggle fadeIn/fadeOut fadeTo animate .

jQuery: Conclusion • lightweight • powerful CSS selectors • ‘less code’ way • built-in effects and animation • transport support (including cross-domain) • a lot of real-life examples .

Questions? .

Dojo .

org .Dojo: Overview http://dojotoolkit.

Dojo: Focus • DOM manipulation • Animations • Ajax • Event and keyboard normalization • Internationalization (i18n) • Widgets .

form. Dijit widgets. and is controlled by dojo. .TitlePane"). DojoX projects.require("dijit. dojo. such as Drag and Drop. This function allows us to pull in parts of the Dojo Toolkit not provided for in the Base dojo. dojo.Dojo: Package system Dojo has a package system built-in to load all the code you need. or even your own code.require("dijit. additional animations.require().js.Button").

addOnLoad(function(){ // our dom is ready.fadeOut({ delay:500 }). .addClass("testClass") // and fade it out after 500 ms .Dojo: Selectors dojo.play().query("#testHeading") // add "testClass" to its class="" attribute . }). get the node: dojo.

dojo. .function(){ this.Dojo: Event handling dojo. })."pointer") . }).function(){ node. }).connect("onclick".connect(node.innerHTML = "I've been clicked".byId("testHeading").innerHTML = "I've been clicked".addOnLoad(function(){ var node = dojo.query("#testHeading") .addOnLoad(function(){ dojo."onclick".style("cursor". dojo. }).

fade it back in contentNode.warn("error!". }.play().xhrGet({ url: "js/sample. load: function(data. onEnd: function(){ // set the data.args){ // fade out the node we're modifying dojo. .Dojo: Ajax transport var init = function(){ var contentNode = dojo. } }). dojo. it goes here: error: function(error. dojo. }.args){ console. } }).byId("content").play(). // if any error occurs.txt". handleAs: "text".innerHTML = data.fadeOut({ node: contentNode. dojo.fadeIn({node: contentNode}).addOnLoad(init).error).

} } }).formSubmit).byId("mainForm").Dojo: Ajax transport // sumbit the form var formSubmit = function(e){ // prevent the form from actually submitting e.php".args){ if(typeof data == "error"){ console. }else{ // show our response console. dojo.log(data). . }).xhrPost({ url: "alternate-submit.preventDefault(). }.connect syntax: call a function directly dojo. handle: function(data.connect(theForm. form: "mainForm"."onsubmit".args).addOnLoad(function(){ var theForm = dojo. // another dojo. // submit the form in the background dojo. handleAs: "text".warn("error!".

CurrencyTextBox" required="true" onChange="updateTotals()" currency="USD"/> dojo.require("dijit.form. dojo. .CurrencyText").00" dojoType="dijit.TextBox").form.TextBox" trim="true" propercase="true" /> Price: <input type="text" maxlength="12" class="fillwidth currency" id="grossincome" name="grossincome" value="0.require("dijit.Dojo: Widgets First Name: <input type="text" size="20" name="first" dojoType="dijit.form.form.

Dojo: Dijit at a Glance ContentPane Slider Textarea Border Container ComboBox CheckBox CurrencyTextBox DateTextBox FilteringSelect TimeTextBox Dialog Toolbar NumberTextBox ValidationTextBox InlineEditBox NumberSpinner Tree AccordionContainer ProgressBar StackContainer Editor TabContainer Menu Grid .

Dojo eXtensions Cometd Cryptography Charting Collections Data Widgets FX Layout Wire Grid Image XML Utilities I/O Offline String Utilities UUID Timing GFX Validate .Dojo: DojoX .

smooshes the layer down with ShrinkSafe 4.Dojo: Dojo custom build 1. groups together modules into layers 2. interns external non-JavaScript files 3. copies all non-layered scripts to the appropriate places .

Dojo: Conclusion • not so lightweight as previous • tons of features • separate packages • custom build .

Questions? .

qooxdoo .

qooxdoo: Overview http://qooxdo.org .

qooxdoo: Focus • One page Rich Internet Applications • A lot of ideas from Qt • OOP approach • No HTML and CSS programming .

qooxdoo: The power is in OOP The main actors of qooxdoo OO are: • Classes • Interfaces • Mixins .

name } } }).test.Class.. statics : { LEGS: 4. } } })...qooxdoo: Classes qx.Cat". . { construct : function() { .Class.test.. { . qx.. { .define("qx.test.Class. makeSound : function() { ..Cat".define("qx.. members: { name : "Kitty".. qx.Cat". getName: function() { return this.define("qx. } }).

.Class. { type : "singleton" .define("qx. { type : "abstract" .test.. qx.Cat".Cat".qooxdoo: Special Types of Classes qx.test..define("qx...Class.Cat".test. { type : "static" . qx.. }).define("qx.. }). }).Class.

callee..define("qx.Animal. } } }).Class.apply(this.Class.test. members: { makeSound : function() { this.debug("I'm a cat"). { members: { makeSound : function(howManyTimes) { .base.define("qx.. { extend: qx. */ arguments. /* howManyTimes or any other parameter are passed. } } }). We .test.qooxdoo: Inheritance qx.Animal"..test. arguments).Cat". don't need to know how many parameters are used. qx.

properties: {"color": {}. .Interface. meth3: function(c) { return qx. }. members: { meth1: function() { return true. statics: { PI : 3. } }.hasInterface(c.test. b) { return arguments.constructor.Class. }).some. staticMethod: function(z) { return typeof z == "string". meth2: function(a.IInterface).14.qooxdoo: Interfaces Defining interface: qx. "name": {} }. }. { extend: [SuperInterfaces].length == 2.ISample". } }.define("qx. qx.

"name": { check: "String"} }.define("qx. }. members: { meth1: function() { return 42.foo() } } }).Class. .qooxdoo: Interfaces Implementing interface: qx.Sample".test.test. meth2: function(a. { implement: [qx. meth3: function(c) { c. properties: { "color": { check: "color"}. b) { return a+b }.ISample].

meth2: function() {} } }). init: -1} }.qooxdoo: Mixins Defining mixin: qx. { include: [SuperMixins].define("name". members: { prop1: "foo".Mixin. properties: { "tabIndex": {check: "Number". meth1: function() {}. .

cool.ui. }).qooxdoo: Mixins Attaching mixin: qx.include(qx.MMixin] . { include : [my.Widget.core.define("my.other. my.MMixin. .Class".cool. qx.Class.MWidgetExtensions). qx.Class...cool.

}).. apply : "applyWidth" } } members : { applyWidth : function(value) { this. } } .. value + "px"). . properties : { width : { check : "Number". widget.getValue().setStyleProperty("width".addEventListener("changeWidth"...qooxdoo: Properties . function(e) { e.innerHTML = "Hello World".

qooxdoo: GUI .

qooxdoo: GUI and even more features • Layouting • Widgets • Interaction • Selection Handling • Drag & Drop • Theming • Low-level Ajax Transport • RPC • Logging and Debugging • Unit testing .

org .qxtransformer http://qxtransformer.qooxdoo: Tooling Generator: • Optimization • Compressing • Internalization • API Documentation • More XML description for UI .

qooxdoo: Real life example http://gmx.com .

Questions? .