Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

I need to write a PhoneGap application with JavaScript and I'm thinking of the code design patterns. I've read some books of JavaScript design patterns but can't really see the advantages/disadvantages on them and I think I don't understand the implementation and usage right.

I would like to have some opinions of which might suit my needs best. I'd like the code to be readable and maintainable.

The application itself is quite small and simple. It has a player management (add/remove), a game management (add/remove players from a team, start/stop/reset a stopwatch).

In last app I created I had over 30 named functions in a global scope which I think is a big no no. So, now I want to make things right, and was thinking of either using an object literal or a module pattern... something like this perhaps:

var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind(); 
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    },

    player: {
        add:            function(name) { ... },
        remove:         function(name) { ... }
    },

    team: {
        addPlayer:      function(name) { ... },
        removePlayer:   function(name) { ... }
    },

    game: {
        create:         function() { ... },
        startTime:      function() { ... },
        stopTime:       function() { ... },
        resetTime:      function() { ... }
    }
};

document.addEventListener('deviceready', MYAPP.init, false);

... or perhaps this?

var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind(); 
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    }
}

var PLAYER = (function () {

    // Some private variables
    var privateVar, privateMethod;

    return {
        add: function (name) { ... },
        remove: function (name) { ... }
    };

}());

document.addEventListener('deviceready', MYAPP.init, false);
share|improve this question
    
Over on StackOverflow there's a question very similar to this: "Examples of practical JavaScript object oriented design patterns". You might want to check out some of the answers there. –  Edward Jul 26 '12 at 21:07
add comment

marked as duplicate by gnat, Kilian Foth, thorsten müller, Jalayn, MichaelT Apr 11 '13 at 13:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers

up vote 7 down vote accepted

Your first example is pretty good. Id recommend the sef-revealing module pattern, it allows you to split your application in files:

(function( MYAPP, $, undefined ) { 

  // we pass in undefined because 'undefined' is no reserved word in Javascript

  'use strict';

  //Private Method
  function addItem( item ) {
    //...
  }  

   //Public Method
   MYAPP.someMethod = function() {
     // ...
   };

}( window.MYAPP = window.MYAPP || {}, jQuery )); 

This way you make shure jQuery or whatever library you want to use is what you expect, and use the same pattern accross several files.

This could work for your application:

(function( MYAPP, $, undefined ) { 
  'use strict';

  // These are private
  var players = [], 
      team = []; 

  // This will be executed at ready event
  $(document).ready(function() {
    bind(); 
  });

  // private Method 
  // (it doesn't need to be public, since the ready 
  // handler shares the same scope)
  function bind() {
    // Bind jQuery click and page events
  }


  MYAPP.player = {
    add: function(name) {
      players.push(name);
    },
    remove: function(name) {
      // ...
    }
  };

  MYAPP.team = {
    addPlayer: function(name) {
      // ...
    },

    removePlayer: function(name) {
      // ...
    }
  };

}( window.MYAPP = window.MYAPP || {}, jQuery )); 

One word to the strict mode. Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

To enable strict mode put this at the top of a program to enable it for the whole script:

"use strict";

Or place it within a function to turn on strict mode only within that context.

function imStrict(){
   "use strict";
   // ... your code ...
}
share|improve this answer
    
I found this example gist.github.com/274388. But I still don't know how should implement those game, player and team 'modules' if I use your, or link's, example. I don't want to break my code into several files. –  micadelli Jul 26 '12 at 21:00
1  
Do you mean function(MYAPP, ...) ? –  kevin cline Jul 26 '12 at 22:20
    
@kevin cline Ah, yes.. To much copy paste :D –  Vain Fellowman Jul 27 '12 at 4:36
add comment

This article is the best I've come across explaining various JS design patters and how they can come together as your application grows. I typically use something similar to the YUI pattern because it's easy for anyone to read and includes private and public methods and properties.

share|improve this answer
add comment

Use the module pattern, use a dependency handling framework (like require.js) during development.

Usually we had this "require" - "provide" duality, and the module pattern, it has satisfied us with a few million lines of client-side JS code (yes, there are some huuge apps out there).

Consider using some of the MVC frameworks like Knockout.JS

Look at how Ext.JS apps are structured perhaps.

Look at how YUI 3 is structured. Yahoo! is also a big user of JavaScript, and they had Crockford on board until quite recently, they know what they do perhaps.

The essential thing about code maintainance are twofold. For every change:

  1. know which file to open
  2. know where to scroll in that file immediately

Now,if you have one, large, single file, you break rule nr. 1.

Otherwise, Uncle Bob's SOLID principles are still adequate, also the usual module handling recommendations from Kevlin Henney. Javascript is just a language.

share|improve this answer
add comment

In last app I created I had over 30 named functions in a global scope which I think is a big no no.

100% correct.

[I] was thinking of either using an object literal or a module pattern.

Sure. Those would be viable patterns.


My thoughts closely align with @Aadaam 's with two caveats:

  1. Here is my favorite JavaScript design patterns link.
  2. I prefer the revealing prototype pattern. My second favorite is the revealing module pattern, which differs slightly from the standard module pattern in that you can declare public/private scope.
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.