Oo Javascript

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

    1 Favorite

    Oo Javascript - Presentation Transcript

    1. OBJECT ORIENTED JAVASCRIPT guida per un mondo migliore Davide Cerbo http://jesty.it Stefano Linguerri http://www.eljeko.net
    2. Una cattiva impressione
    3. L'unione fa la forza JAVASCRIPT + PROTOTYPE
    4. Perché usare Prototype
      • Codice più breve
      • Sintassi più chiara
      • Gestisce le incompatibilità trai vari browser
      • Fornisce diverse funzioni e oggetti di utilità
      • Permette lo sviluppo di Javascript non intrusivo
      • E' complementare a Script.aculo.us
    5. Qualcosa di utile
      • $('...') -> come getDocumentById('...') ma ritorna un Element di Prototype
      • $$('...') -> Selettore CSS $$('.menu #submenu) ritorna tutti gli elementi che hanno class submenu all'interno di un elemento che ha id menu
      • Ajax.request(Url, {...}) -> Esegue una richiesta AJAX, le graffe conterranno le opzioni della request: new Ajax.Request(url, {onSuccess: function(transport) {...}); Esistono anche altri metodi come: updater e periodicalUpdater.
      • Template -> Permette di definire delle stringe parametrizzabili var t = new Template('Name: #{name}, surname: #{surname}'); var show = {name: 'Davide', surname: 'Cerbo'}; t.evaluate(show); //return “Name: Davide, surname: Cerbo”
      • Observer -> Permette di osservare gli eventi su un elemento $('id').observe('click', function(element){...});
    6. Di cosa abbiamo bisogno?
      • Per considerare JAVASCRIPT un linguaggio Object Oriented abbiamo bisogno di:
      • Strutture dati complesse
      • Classi
      • Interfacce
      • Polimorfismo
    7. Strutture dati complesse
      • Hash -> var h = new Hash(); h.set(“key”, “value”); h.get(“key”); //return “value” h.unset(“key”); h.toQueryString() //return “key1=v1&key2=v2&...”
      • Enumerable -> sono liste iterabili con metodi come each, map, find, select, etc... $A(...).each(function(e){ alert(e.id); }); $$('...') restituisce un Enumerable
      Sono tutte CLOSURE
    8. Questione di classe
      • Javascript Classico
      var Person = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }; var jack = new Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy!
      • Prototype
      var Person = Class.create({ initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }); var jack = new Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy!
    9. Estendiamo
      • Javascript classico
      var Pirate = Class.create(); Pirate.prototype = Object.extend(new Person(), { say: function(message) { return this.name + ': ' + message + ', yarr!'; } });
      • Prototype
      var Pirate = Class.create(Person, { say: function($super, message) { return $super(message) + ', yarr!'; } }); new Pirate (“Jack Maffai”).say(“Hi Boy!”); //say return: Hi Boy!, yarr!
    10. Interfacce? Non ci sono e basta! Accontentiamoci delle classi E ricordiamoci che in Javascript vige la regola: “ If it walks like a duck and quacks like a duck, I would call it a duck.”
    11. Al volo var john = new Pirate('Long John'); john.sleep(); // -> ERROR: sleep is not a method Person.addMethods({ sleep: function() { return this.say('ZzZ'); } }); john.sleep(); // -> "Long John: ZzZ, yarr!" Il metodo viene aggiunto a tutte le istanze e le sottoclassi di Pirate
    12. DOMinare con Prototype Questo approccio deve cambiare il nostro modo di vedere la programmazione Javascript PROGRAMMAZIONE FUNZIONALE
    13. Esempio
      • HTML:
      <table id=&quot;simonboard&quot;> <TR> <TD id=&quot;red&quot;></TD> <TD id=&quot;blue&quot;></TD> <TD id=&quot;fuchsia&quot;></TD> </TR> <TR> <TD id=&quot;black&quot;></TD> <TD id=&quot;green&quot;></TD> <TD id=&quot;aqua&quot;></TD> </TR> <TR> <TD id=&quot;gold&quot;></TD> <TD id=&quot;magenta&quot;></TD> <TD id=&quot;coral&quot;></TD> </TR> </table>
      • Script di startup:
      <script language=&quot;JavaScript&quot;> // $('simonboard') -> indica la tabella // 5 -> il numero massimo di quadrati da colorare new Board($('simonboard')).start(5); </script> Il colore predefinito per il quadrato Tabella da utilizzare
    14. Lo script var Tile = Class.create({ initialize: function(color, element) { this.color = color; this.element = element; }, blink: function() { this.element.style.backgroundColor = this.color; new Effect.Opacity(this.element, {duration:2, from:1.0, to:0}); // Scrip.aculo.us } }); var Board = Class.create({ initialize: function(boardElement) { this.tiles = boardElement.select(&quot;td&quot;).map(function(element){ return new Tile(element.id, element); }); }, //numero massimo di blocchi da colorare start: function(steps) { var boardSize = this.tiles.length; var tempTiles = this.tiles; //serve per problemi di scope si corregge usando la funzione bind() $R(1, steps).each(function(i){ //funzione di Prototype che riempe un array con un range di valori var index = Math.ceil(Math.random() * boardSize); var tile = tempTiles[index-1]; window.setTimeout(function() { tile.blink(); }, 500 * index); }); } });
    15. Un concetto utile: bind start: function(steps) { var boardSize = this.tiles.length; $R(1, steps).each(function(i) { var index = Math.ceil(Math.random() * boardSize); var tile = this.tiles[index-1]; window.setTimeout(function() { tile.blink(); }, 500 * index); } .bind(this) ); } Il bind serve ad evitare problemi di scope, se lo avessi omesso il this considerato dalla funzione sarebbe stato l'oggeto window . In Javascript tutte le funzioni sono eseguite in un determinato contesto e questo è referenziabile tramite la parola chiave da this Le funzioni utilizzate come closure sono funzioni globali, quindi hanno il contesto globale
    16. Strumenti utili
      • Log4J
      • Debugger
      • JUnit
      • JMock e simili
      • BlackbirdJS
      • Firebug
      • JSUnit
      • JSMock
      Siamo abituati ad avere una marea di strumenti a nostra disposione javascript non ci deluderà!
    17. Logging: Log4J -> BlackbirdJS
    18. Debug: Java Debugger -> Firebug
    19. Unit Test: JUnit -> JSUnit [1]
    20. Unit Test: JUnit -> JSUnit [2]
    21. Unit Test: JUnit -> JSUnit [3]
    22. Unit Test: JUnit -> JSUnit [4]
    23. MockObject: JMock -> JSMock [1]
      • Classe sotto test (CUT)
      function Worker() { this.getValue = function() { /* ... */} this.isFinished = function() {/* ... */} }
      • Fixture
      function doWork(worker) { if(worker.isFinished()) { return worker.getValue(); } else { return null; } }
      • Test
      function test_doWork() { var mControl = new MockControl(); worker = mControl.createMock(Worker); worker.expects().isFinished().andReturn(true); worker.expects().getValue().andReturn('hello'); var result = doWork(worker); assertEquals('hello', result); mControl.verify(); }
    24. MockObject: JMock -> JSMock [2]
      • Classe sotto test (CUT)
      function Worker() { this.getValue = function() { /* ... */} this.isFinished = function() {/* ... */} }
      • Fixture
      function doWork(worker) { if(worker.isFinished()) { return worker.getValue(); } else { return null; } }
      • Test
      function test_doWork_null() { var mControl = new MockControl(); worker = mControl.createMock(Worker); worker.expects().isFinished().andReturn(false); var result = doWork(worker); assertNull(result); mControl.verify(); }
    25. Conclusioni
    26. Bibliografia & Links
      • www.prototypejs.org
      • http://script.aculo.us
      • http://www.prototypejs.org/learn/class-inheritance
      • http://www.gscottolson.com/blackbirdjs/
      • http://getfirebug.com/js.html
      • http://www.jsunit.net/
      • http://jsmock.sourceforge.net/
      • http://www.infoq.com/articles/javascript-tdd
      • http://en.wikipedia.org/wiki/Duck_typing
      • http://www.prototypejs.org/api/function/bind
      • http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding
    27. Q&A JS? http://jesty.it [email_address] [email_address]
    SlideShare Zeitgeist 2009

    + maraexceptionmaraexception Nominate

    custom

    541 views, 1 favs, 1 embeds more stats

    by Davide Cerbo e Stefano Linguerri.
    Javascript vi more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 541
      • 519 on SlideShare
      • 22 from embeds
    • Comments 0
    • Favorites 1
    • Downloads 15
    Most viewed embeds
    • 22 views on http://www.jugroma.it

    more

    All embeds
    • 22 views on http://www.jugroma.it

    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