Peter Michaux has shared how he structures his code these days, as he has settled on a pattern:
The code example below is a simple little logger widget. It appends messages to a list and has a clear link to delete all the recorded messages.
PLAIN TEXT
JAVASCRIPT:
1.
2.
// Wrap code with module pattern.
3.
(function() {
4.
var global = this;
5.
6.
// helper functions
7.
var sanatize = function(msg) {
8.
return (String(msg)).replace('&', '&').replace('<', '<').replace('>', '>');
9.
};
10.
11.
// widget constructor function
12.
global.MY_makeLogger = function() {
13.
14.
// private instance methods
15.
var clear = function() {
16.
LIB_emptyElement(logEl);
17.
};
18.
var append = function(msg, className) {
19.
LIB_insertBottom(logEl,
20.
'<dt class="'+className+'">' + (new Date()) + '</dt>' +
21.
'<dd class="'+className+'">' + sanatize(msg) + '</dd>');
22.
};
23.
24.
// create widget DOM fragment
25.
var parser = document.createElement('div');
26.
LIB_upateElement(parser,
27.
'<div class="Logger">' +
28.
'<p><a href="#" class="clearLink">clear</a></p>' +
29.
'<dl class="log"></dl>' +
30.
'</div>');
31.
32.
// find pieces and enliven DOM fragment
33.
var rootEl = LIB_find('.Logger', parser)[0];
34.
parser = null; // enable garbage collection of parser div
35.
var logEl = LIB_find('.log', rootEl)[0];
36.
LIB_on(LIB_find('.clearLink', rootEl), 'click', function(e) {
37.
LIB_preventDefault(e);
38.
clear();
39.
});
40.
41.
// public instance methods
42.
return {
43.
getRootEl: function() {return rootEl;},
44.
log : function(msg) {append(msg, 'log' );},
45.
warn : function(msg) {append(msg, 'warn' );},
46.
error : function(msg) {append(msg, 'error');}
47.
};
48.
49.
};
50.
})();
51.
He talks about how he uses naming conventions to keep track of library functions, exported functions, gensym ids.
source: ajaxian