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