JavaScript Libraries Overview

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    4 Favorites

    JavaScript Libraries Overview - Presentation Transcript

    1. JavaScript Libraries Overview Siarhei Barysiuk s.barysiuk@sam-solutions.net
    2. Our roadmap
    3. Libraries: What we will cover today... 5 great open source libraries for your project. • prototype • jQuery • dojo • qooxdoo
    4. Libraries: General picture Global picture Lightweight Widgets One-page Applications
    5. Prototype
    6. Prototype: Overview http://prototypejs.org
    7. Prototype: Focus • DOM manipulation • Ajax transport • Utility methods for built-in objects • Class-based OOP
    8. Prototype: DOM manipulation Say goodbye to getElementById() document.getElementById(\"id\").innerHTML = \"<li>node</li>\"; Say hello to $() $(\"id\").innerHTML = \"<li>node</li>\"; $(element) extended DOM element
    9. Prototype: DOM Element extension * extend * makePositioned * absolutize * select * fire * match * addClassName * setOpacity * firstDescendant * next * addMethods * setStyle * getDimensions * nextSiblings * adjacent * show * getElementsByClassName * observe * ancestors * siblings * getElementsBySelector * positionedOffset * childElements * stopObserving * getHeight * previous * classNames * toggle * getOffsetParent * previousSiblings * cleanWhitespace * toggleClassName * getStyle * readAttribute * clonePosition * undoClipping * getWidth * recursivelyCollect * cumulativeOffset * undoPositioned * hasClassName * relativize * cumulativeScrollOffset * up * hide * remove * descendantOf * update * identify * removeClassName * descendants * viewportOffset * immediateDescendants * replace * down * visible * insert * scrollTo * empty * wrap * inspect * writeAttribute * makeClipping $('message').addClassName('read').update('I read this message!').setStyle({opacity: 0.5});
    10. Prototype: Creating a DOM element The old way: var a = document.createElement('a'); a.setAttribute('class', 'foo'); a.setAttribute('href', '/foo.html'); a.appendChild(document.createTextNode(\"Next page\")); The new way: var a = new Element('a', { 'class': 'foo', href: '/foo.html' }).update(\"Next page\");
    11. Prototype: Even more bucks $((id | element)...) -> [HTMLElement...] $$(cssRule...) -> [HTMLElement...] $A(iterable) -> actualArray $F(element) -> value $H([obj]) -> Hash $R(start, end[, exclusive = false]) -> ObjectRange $w(String) -> Array
    12. Prototype: Event handling $('foo').observe('click', respondToClick); function respondToClick(event) { var element = event.element(); element.addClassName('active'); }
    13. Prototype: Ajax transport new Ajax.Request('/some_url',{ method:'get', onSuccess: function(transport){ var response = transport.responseText || \"no response text\"; alert(\"Success! \\n\\n\" + response); }, onFailure: function(){ alert('Something went wrong...') } }); Also available are onXXX callbacks, where XXX is the HTTP response status like 200 or 404.
    14. Prototype: Ajax transport new Ajax.Request('/some_url', { method: 'get', parameters: {company: 'example', limit: 12} }); new Ajax.Request('/some_url', { parameters: $('id_of_form_element').serialize(true) }); form serialization
    15. Prototype: Ajax magic new Ajax.Updater( { success: 'products', 3.1 failure: 'errors' 3.2 }, '/some_url', 1 { method: 'get', 2 insertion: Insertion.Top 4 } );
    16. Prototype: Built-in object extensions * all * any * collect var myObject = {}; * detect * each * eachSlice ['foo', 'bar', 'baz'].each(function(name, index) { * entries this[name] = index; * find }, myObject); // we have specified the context * findAll * grep * inGroupsOf myObject * include * inject //-> { foo: 0, bar: 1, baz: 2} * invoke * map * max * member * min * partition * pluck * reject * select * size * sortBy * toArray * zip
    17. Prototype: Built-in object extensions * blank * camelize * capitalize * dasherize \"<h1>hello, i'm HTML</h1>\".escapeHTML() * empty * endsWith //-> \"&lt;h1&gt;hello, i'm HTML&lt;/h1&gt;\" * escapeHTML * evalJSON * evalScripts 'background-color'.camelize(); // -> 'backgroundColor' * extractScripts * gsub * include 'Prototype framework'.include('frame'); //-> true * inspect 'Prototype framework'.include('frameset');//-> false * interpolate * isJSON * parseQuery * scan \"echo \".times(3); //-> \"echo echo echo \" * startsWith * strip * stripScripts \"#{animals} on a #{transport}\".interpolate({ * stripTags animals: \"Pigs\", * sub * succ transport: \"Surfboard\" }); * times //-> \"Pigs on a Surfboard\" * toArray * toJSON * toQueryParams * truncate * underscore * unescapeHTML * unfilterJSON
    18. 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!\"
    19. Prototype: Real life example http://gmx.com http://web.de http://gmx.de
    20. Prototype: Conclusion • lightweight • good for small projects • a lot of useful methods • transport support • effects with script.aculo.us • good documented • a lot of real project which use prototype
    21. Questions?
    22. jQuery
    23. jQuery: Overview http://jquery.com
    24. jQuery: Focus Motto: Write less, do more. • DOM manipulation • Ajax transport • Effects • Other functionality with plugins
    25. jQuery: DOM manipulation Very powerful selectors. $(\"#myDiv\").css(\"border\",\"3px solid red\"); $(\"div\").css(\"border\",\"3px solid red\"); $(\".myClass\").css(\"border\",\"3px solid red\"); $(\"*\").css(\"border\",\"3px solid red\"); $(\"div,span,p.myClass\").css(\"border\",\"3px solid red\");
    26. jQuery: DOM manipulation Even more powerful than you expect. $('li:eq(0)') $('li:even') $('li:lt(3)') $('li:not(.goofy)') $('p a[href*=#]') $('code, li.goofy') $('ol .goofy > strong') $('li + li > a[href$=pdf]') $('span:hidden')
    27. jQuery: DOM manipulation Attributes: Text: attr( name ) text( ) attr( properties ) text( val ) attr( key, value ) HTML: attr( key, value ) removeAttr( name ) html( ) Classes: html( val ) addClass( class ) Value: hasClass( class ) removeClass( class ) val( ) toggleClass( class ) val( val )
    28. jQuery: DOM manipulation append( content ) appendTo( content ) prepend( content ) prependTo( content ) after( content ) before( content ) insertAfter( content ) insertBefore( content ) wrap( html ) replaceWith( content ) clone( )
    29. jQuery: Events Very convenient event handling system. 3 main methods: bind( type, data, fn ) trigger( type, data ) unbind( type, data )
    30. jQuery: Binding event handlers $(\"p\").bind(\"click\", function(e){ var str = \"( \" + e.pageX + \", \" + e.pageY + \" )\"; $(\"span\").text(\"Click happened! \" + str); }); $(\"p\").bind(\"dblclick\", function(){ $(\"span\").text(\"Double-click happened in \" + this.tagName); }); $(\"p\").bind(\"mouseenter mouseleave\", function(e){ $(this).toggleClass(\"over\"); }); $(\"p\").trigger(\"click\");
    31. jQuery: Binding event handlers $(\"p\").click(function(e){ var str = \"( \" + e.pageX + \", \" + e.pageY + \" )\"; $(\"span\").text(\"Click happened! \" + str); }); $(\"p\").dblclick(function(){ $(\"span\").text(\"Double-click happened in \" + this.tagName); }); $(\"p\").click();
    32. jQuery: Custom events $(\"p\").bind(\"myCustomEvent\", function(e, myName, myValue){ $(this).text(myName + \", hi there!\"); $(\"span\").stop().css(\"opacity\", 1) .text(\"myName = \" + myName) .fadeIn(30).fadeOut(1000); }); $(\"button\").click(function () { $(\"p\").trigger(\"myCustomEvent\", [ \"John\" ]); });
    33. jQuery: onload event $(document).ready(function () { $(\"p\").text(\"The DOM is now loaded and can be manipulated.\"); });
    34. jQuery: Ajax transport $.ajax({ type: \"POST\", url: \"some.php\", data: \"name=John&location=Boston\", success: function(msg){ alert( \"Data Saved: \" + msg ); } }); $.ajax({ url: \"test.html\", cache: false, success: function(html){ $(\"#results\").append(html); } });
    35. jQuery: Ajax transport $.ajax({ url:\"http://api.flickr.com/services/feeds/photos_public.gne? tags=cat&tagmode=any&format=json\", dataType:\"jsonp\", jsonp:\"jsoncallback\", success: function(data){ //... }) } })
    36. jQuery: Effects show/hide toggle slideDown/slideUp slideToggle fadeIn/fadeOut fadeTo animate
    37. 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
    38. Questions?
    39. Dojo
    40. Dojo: Overview http://dojotoolkit.org
    41. Dojo: Focus • DOM manipulation • Animations • Ajax • Event and keyboard normalization • Internationalization (i18n) • Widgets
    42. Dojo: Package system Dojo has a package system built-in to load all the code you need, and is controlled by dojo.require(). This function allows us to pull in parts of the Dojo Toolkit not provided for in the Base dojo.js, such as Drag and Drop, additional animations, Dijit widgets, DojoX projects, or even your own code. dojo.require(\"dijit.form.Button\"); dojo.require(\"dijit.TitlePane\");
    43. Dojo: Selectors dojo.addOnLoad(function(){ // our dom is ready, get the node: dojo.query(\"#testHeading\") // add \"testClass\" to its class=\"\" attribute .addClass(\"testClass\") // and fade it out after 500 ms .fadeOut({ delay:500 }).play(); });
    44. Dojo: Event handling dojo.addOnLoad(function(){ var node = dojo.byId(\"testHeading\"); dojo.connect(node,\"onclick\",function(){ node.innerHTML = \"I've been clicked\"; }); }); dojo.addOnLoad(function(){ dojo.query(\"#testHeading\") .style(\"cursor\",\"pointer\") .connect(\"onclick\",function(){ this.innerHTML = \"I've been clicked\"; }); });
    45. Dojo: Ajax transport var init = function(){ var contentNode = dojo.byId(\"content\"); dojo.xhrGet({ url: \"js/sample.txt\", handleAs: \"text\", load: function(data,args){ // fade out the node we're modifying dojo.fadeOut({ node: contentNode, onEnd: function(){ // set the data, fade it back in contentNode.innerHTML = data; dojo.fadeIn({node: contentNode}).play(); } }).play(); }, // if any error occurs, it goes here: error: function(error,args){ console.warn(\"error!\",error); } }); }; dojo.addOnLoad(init);
    46. Dojo: Ajax transport // sumbit the form var formSubmit = function(e){ // prevent the form from actually submitting e.preventDefault(); // submit the form in the background dojo.xhrPost({ url: \"alternate-submit.php\", form: \"mainForm\", handleAs: \"text\", handle: function(data,args){ if(typeof data == \"error\"){ console.warn(\"error!\",args); }else{ // show our response console.log(data); } } }); }; dojo.addOnLoad(function(){ var theForm = dojo.byId(\"mainForm\"); // another dojo.connect syntax: call a function directly dojo.connect(theForm,\"onsubmit\",formSubmit); });
    47. Dojo: Widgets First Name: <input type=\"text\" size=\"20\" name=\"first\" dojoType=\"dijit.form.TextBox\" trim=\"true\" propercase=\"true\" /> Price: <input type=\"text\" maxlength=\"12\" class=\"fillwidth currency\" id=\"grossincome\" name=\"grossincome\" value=\"0.00\" dojoType=\"dijit.form.CurrencyTextBox\" required=\"true\" onChange=\"updateTotals()\" currency=\"USD\"/> dojo.require(\"dijit.form.TextBox\"); dojo.require(\"dijit.form.CurrencyText\");
    48. Dojo: Dijit at a Glance Border Container AccordionContainer ContentPane Toolbar Slider ComboBox CurrencyTextBox NumberTextBox CheckBox DateTextBox Textarea ValidationTextBox FilteringSelect InlineEditBox TimeTextBox TabContainer NumberSpinner StackContainer Menu Dialog Tree ProgressBar Editor Grid
    49. Dojo: DojoX - Dojo eXtensions Cometd Cryptography Widgets Charting FX Data Layout Collections Wire Grid I/O Image Timing XML Utilities Offline GFX String Utilities Validate UUID
    50. Dojo: Dojo custom build 1. groups together modules into layers 2. interns external non-JavaScript files 3. smooshes the layer down with ShrinkSafe 4. copies all non-layered scripts to the appropriate places
    51. Dojo: Conclusion • not so lightweight as previous • tons of features • separate packages • custom build
    52. Questions?
    53. qooxdoo
    54. qooxdoo: Overview http://qooxdo.org
    55. qooxdoo: Focus • One page Rich Internet Applications • A lot of ideas from Qt • OOP approach • No HTML and CSS programming
    56. qooxdoo: The power is in OOP The main actors of qooxdoo OO are: • Classes • Interfaces • Mixins
    57. qooxdoo: Classes qx.Class.define(\"qx.test.Cat\", { construct : function() { ... } }); qx.Class.define(\"qx.test.Cat\", { ... statics : { LEGS: 4, makeSound : function() { ... } } }); qx.Class.define(\"qx.test.Cat\", { ... members: { name : \"Kitty\", getName: function() { return this.name } } });
    58. qooxdoo: Special Types of Classes qx.Class.define(\"qx.test.Cat\", { type : \"static\" ... }); qx.Class.define(\"qx.test.Cat\", { type : \"abstract\" ... }); qx.Class.define(\"qx.test.Cat\", { type : \"singleton\" ... });
    59. qooxdoo: Inheritance qx.Class.define(\"qx.test.Animal\", { members: { makeSound : function(howManyTimes) { .... } } }); qx.Class.define(\"qx.test.Cat\", { extend: qx.test.Animal, members: { makeSound : function() { this.debug(\"I'm a cat\"); /* howManyTimes or any other parameter are passed. We don't need to know how many parameters are used. */ arguments.callee.base.apply(this, arguments); } } });
    60. qooxdoo: Interfaces Defining interface: qx.Interface.define(\"qx.test.ISample\", { extend: [SuperInterfaces], properties: {\"color\": {}, \"name\": {} }, members: { meth1: function() { return true; }, meth2: function(a, b) { return arguments.length == 2; }, meth3: function(c) { return qx.Class.hasInterface(c.constructor, qx.some.IInterface); } }, statics: { PI : 3.14, staticMethod: function(z) { return typeof z == \"string\"; } }, });
    61. qooxdoo: Interfaces Implementing interface: qx.Class.define(\"qx.test.Sample\", { implement: [qx.test.ISample], properties: { \"color\": { check: \"color\"}, \"name\": { check: \"String\"} }, members: { meth1: function() { return 42; }, meth2: function(a, b) { return a+b }, meth3: function(c) { c.foo() } } });
    62. qooxdoo: Mixins Defining mixin: qx.Mixin.define(\"name\", { include: [SuperMixins], properties: { \"tabIndex\": {check: \"Number\", init: -1} }, members: { prop1: \"foo\", meth1: function() {}, meth2: function() {} } });
    63. qooxdoo: Mixins Attaching mixin: qx.Class.define(\"my.cool.Class\", { include : [my.cool.MMixin, my.other.cool.MMixin] ... }); qx.Class.include(qx.ui.core.Widget, qx.MWidgetExtensions);
    64. qooxdoo: Properties ... properties : { width : { check : \"Number\", apply : \"applyWidth\" } } members : { applyWidth : function(value) { this.setStyleProperty(\"width\", value + \"px\"); } } ... widget.addEventListener(\"changeWidth\", function(e) { e.getValue().innerHTML = \"Hello World\"; });
    65. qooxdoo: GUI
    66. qooxdoo: GUI and even more features • Layouting • Widgets • Interaction • Selection Handling • Drag & Drop • Theming • Low-level Ajax Transport • RPC • Logging and Debugging • Unit testing
    67. qooxdoo: Tooling Generator: • Optimization • Compressing • Internalization • API Documentation • More XML description for UI - qxtransformer http://qxtransformer.org
    68. qooxdoo: Real life example http://gmx.com
    69. Questions?

    + Siarhei BarysiukSiarhei Barysiuk, 10 months ago

    custom

    2118 views, 4 favs, 2 embeds more stats

    Day 1 of 7-days "JavaScript and Rich User Interface more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 2118
      • 2108 on SlideShare
      • 10 from embeds
    • Comments 0
    • Favorites 4
    • Downloads 88
    Most viewed embeds
    • 9 views on http://mrthangaraj.blogspot.com
    • 1 views on http://www.blogger.com

    more

    All embeds
    • 9 views on http://mrthangaraj.blogspot.com
    • 1 views on http://www.blogger.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories