I've developed a template to modularize JavaScript code I write for client work. The example below is a simple class with 1 attribute and 3 functions.
Rationale:
- Standardized constructor to add or modify settings/ options
- Functions as variables used later to return only "public" functions, all else are private
- Using local "call" variable to easily replace functions in unit testing
Are there any improvements you can recommend or general best practices to look for in terms of improvement?
var dataStatus = function( constructorOptions )
{
"use strict";
var options = {
displayId: 'dataStatus',
statii: {
'settingUp': {
tooltip: 'Setting Up...',
color: '808080'
},
'loading': {
tooltip: 'Data Loading...',
color: '99ee90'
},
'loaded': {
tooltip: 'Data Loaded',
color: '006400'
},
'changed': {
tooltip: 'Data Changed',
color: '8b0000'
},
'saving': {
tooltip: 'Saving...',
color: 'ffd700'
}
},
defaultStatus: 'settingUp'
};
var local = {
status: false
};
var init = function( optionsToSet )
{
jQuery.extend( options, optionsToSet);
call.setStatus( options.defaultStatus );
return this;
};
var inject = function (functionToReplace, injectedFunction)
{
call[functionToReplace] = injectedFunction;
return injectedFunction;
};
var getStatus = function()
{
return local.status;
};
var setStatus = function( status, signal )
{
local.status = status;
if (typeof signal == 'undefined' || signal != false){
call.signal( call.getStatus() );
}
};
var signal = function ( status ){
if (status in options.statii){
jQuery( '#' + options.displayId )
.html( '<i class="fa fa-circle" title="' + options.statii[status].tooltip + '"></i>')
.css( 'color', '#' + options.statii[status].color )
.css( 'background-color', '#ffffff');
}
};
var call = {
init: init,
options: options,
inject: inject,
getStatus: getStatus,
setStatus: setStatus,
signal: signal
};
if(typeof myPublicTestNamespace == "undefined"){//http://stackoverflow.com/a/9172377/123594
return {
init: init,
getStatus: getStatus,
setStatus: setStatus,
signal: signal
};
}else{
return call;
};
init( constructorOptions );
};