JavaScript application design patterns [duplicate]

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);

1

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 ...
}

3

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.

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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật