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

JavaScript Design Patterns

Lawren
July 30, 2015

JavaScript Design Patterns

Design patterns enable us to stand on the shoulders of giants, that is, help us build off of the knowledge of the programmers before us and avoid many of the same pitfalls that may have set them back.

In this talk, we will discuss the importance and basics of JavaScript design patterns and anti-patterns as we explore a handful of the more common ones being used today.

We’ll take a look at the Module, Revealing Module, Facade and Abstraction patterns, and they’re usefulness in plugin and application development. You can also expect a brief refresher on closures, if you’re into that sort of thing.

Lawren

July 30, 2015
Tweet

More Decks by Lawren

Other Decks in Programming

Transcript

  1. “TO WORK OUR WAY TOWARDS A SHARED LANGUAGE ONCE AGAIN,

    WE MUST FIRST LEARN HOW TO DISCOVER PATTERNS WHICH ARE DEEP, AND CAPABLE OF GENERATING LIFE.” - CHRISTOPHER ALEXANDER
  2. FUNCTIONS CAN ENCAPSULATE THEIR ENVIRONMENT. var inc = (function ()

    {
 var counter = 0;
 return function() { console.log(++counter); };
 })();
 
 inc(); //logs 1
 inc(); //logs 2
  3. var inc = (function () {
 var counter = 0;


    return function() { console.log(++counter); };
 })();
 
 inc(); //logs 1
 inc(); //logs 2 THIS IS A CLOSURE.
  4. <!doctype html>
 <html>
 <head></head>
 <body>
 <!-- all our markup... —>

    <script src="js/plugins.js"></script>
 <script src="js/main.js"></script>
 </body>
 </html> 
 <!-- by moving all of our scripts to
 the bottom of our page we ensure
 our page load continues uninterrupted -->
  5. $('.item-1').hover(function() {
 $('#item-info-1').stop().slideToggle(400);
 }, function() {
 $('#item-info-1').hide();
 });
 
 $('.item-2').hover(function()

    {
 $('#item-info-2').stop().slideToggle(400);
 }, function() {
 $('#item-info-2').hide();
 });
 
 $('.item-3').hover(function() {
 $('#item-info-3').stop().slideToggle(400);
 }, function() {
 $('#item-info-3').hide();
 });
  6. $('div[class^=item]').hover(function() {
 var cls = $(this).attr('class').replace('item', "")
 $('#item-info' + cls).stop().slideToggle(400);


    }, function() {
 $('#item-info' + cls).hide();
 }); 
 // we can avoid repetition by targeting
 // all items at once and then stashing
 // the item’s id to determine what info
 // pane we want to show
  7. var arra = [];
 for (var i = 0; i

    < 2003000; i++) {
 arra.push(i * i + i);
 } // if left to the window this will use // up roughly 10mb of memory usage
  8. (function(){
 var arra = [];
 for (var i = 0;

    i < 2003000; i++) {
 arra.push(i * i + i);
 }
 })(); 
 // by simply wrapping our function
 // in a closure we have ensured it
 // will be garbage collected
  9. var level = ['Senior', 'Junior', 'Principal'];
 
 function getLevel ()

    {
 return level[(~~(Math.random()*level.length))];
 }
 
 var role = ['Analyst','Architect','Consultant'];
 
 function getrole () {
 return role[(~~(Math.random()*role.length))];
 }
  10. var level = ['Senior', 'Junior', 'Principal'],
 role = ['Analyst','Architect','Consultant'];
 


    function getLevel () {
 return level[(~~(Math.random()*level.length))];
 }
 function getRole () {
 return role[(~~(Math.random()*role.length))];
 } 
 // utilizing hoisting, we can organize our code
 // and keep our variables and functions
 // separated, clean, and organized
  11. MODULE PATTERN ๏ Helps keep code organized ๏ Encapsulates your

    code ‣ Hidden from other scopes ‣ Non-polluting
  12. var myModule = (function() {
 
 var dict = {

    //private variables
 level: ['Senior','Junior','Principal'],
 role: ['Analyst','Architect','Consultant']
 };
 
 return {
 randomWord: function(arr) {
 arr = dict[arr];
 console.log(arr[(~~(Math.random()*arr.length))]);
 }
 };
 
 })();
 
 myModule.randomWord('role'); //logs a random role
 myModule.randomWord('level'); //logs a random level
  13. REVEALING MODULE PATTERN ๏ Allows for better organization of public

    and private “classes” ๏ Enables easy abstraction ‣ Can greatly improve the ease of use of otherwise complex functionality
  14. var myModule = (function() {
 
 var dict = {

    //now private
 level: ['Senior','Junior','Principal'],
 role: ['Analyst','Architect','Consultant']
 };
 
 function randomWord(arr) {
 arr = dict[arr];
 console.log(arr[(~~(Math.random()*arr.length))]);
 }
 
 return {
 word: randomWord
 };
 
 })();
 
 myModule.word('role'); //logs a random role
 myModule.word('level'); //logs a random level

  15. FACADE/ABSTRACTION PATTERN ๏ Simplifies use of complex subsystems ‣ Can

    decrease future development time ‣ Often less prone to errors than when manipulating subsystems directly
  16. var myModule = (function() {
 
 var _private = {


    i: 5,
 get: function() {
 console.log( "current value:" + this.i);
 },
 set: function( val ) {
 this.i = val;
 },
 run: function() {
 console.log( "running" );
 }
 };
 
 return {
 facade: function( args ) {
 _private.set(args.val);
 _private.get();
 if ( args.run ) {
 _private.run();
 }
 }
 };
 }());
 
 myModule.facade({run: true, val: 10}); //returns "current value: 10" and "running"