Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Design Patterns

JavaScript Design Patterns

A talk illustrating the use of a few simple JavaScript design patterns to create complex systems and improve overall code quality.

Originally given at Jersey Shore Tech on April 15, 2014.

Anthony Colangelo

April 15, 2014
Tweet

More Decks by Anthony Colangelo

Other Decks in Programming

Transcript

  1. JavaScript Design Patterns Credit: http://mantia.me

  2. Reusable solutions to commonly-occurring problems.

  3. Relationships

  4. Module Pattern

  5. None
  6. activate: function() { // ... } activeClass: 'current' var pageDot

    = { }; ,
  7. function activate() { // ... } var pageDot = (function(){

    var activeClass = 'current'; })();
  8. None
  9. Revealing Module
 Pattern

  10. ! // ... })(); var pageDot = (function(){

  11. ! // ... })(); var pageDot = (function(){ return {

    };
  12. ! // ... })(); var pageDot = (function(){ return {

    activate: activate }; ! pageDot.activate();
  13. }; return { activate: activate, deactivate: deactivate, isActive: function() {

    // ... }
  14. None
  15. Constructor Pattern

  16. function PageDot() { ! // ... ! } ! var

    pageDot = new PageDot();
  17. function PageDot(element) { ! // ... ! } ! var

    pageDot = new PageDot( ); document.querySelector('.dot-1')
  18. dots = document.querySelectorAll('.dot'); var pageDots = [], ! for (var

    i = 0; i < dots.length; i++) { } pageDots.push( new PageDot(dots[i]) );
  19. None
  20. Facade Pattern

  21. None
  22. Pagination PageDot PageDot PageDot PageArrow PageArrow

  23. }; } function Pagination() { // ... ! return {

    next: function() { }
  24. function Pagination() { // ... ! return { next: function()

    { }; } } pageDots[previousPage].deactivate(); pageDots[currentPage].activate();
  25. None
  26. Observer Pattern

  27. var pagination = new Pagination() slideViewer = new SlideViewer();

  28. var pagination = new Pagination() slideViewer = new SlideViewer(); !

    pagination.addObserver(slideViewer);
  29. function Pagination() { var observers = []; ! function addObserver(observer)

    { observers.push(observer); } // ... }
  30. function Pagination() { // ... function notifyObservers(action, data) { for

    (var i = 0; i < observers.length; i++) { observers[i].update(action, data); } } // ... }
  31. function Pagination() { // ... ! return { next: function()

    { pageDots[previousPage].deactivate(); pageDots[currentPage].activate(); notifyObservers('navigate', currentPage); } }; }
  32. function SlideViewer() { ! function update(action, data) { // ...

    } ! // ... ! }
  33. var pagination = new Pagination() slideViewer = new SlideViewer(); !

    pagination.addObserver(slideViewer);
  34. Relationships

  35. Learning JavaScript Design Patterns Addy Osmani

  36. @acolangelo