JavaScript code organization
Preface
Hi. I am a follower of functional programming, and I like the simplicity and readability of code. Every time I write any part of the application, I imagine that I am creating a thing. This thing must have certain details and they have to stand in the right places. So all these things are similar to each other and form one large application.
I am a JavaScript-developer. I think it's a great language with expressive features. Someone said that the language is not enough elements of the OOP, so JS can not be taken seriously. I'm pretty sure that JS has one of the best implementations of functional programming.
Template
Based on my experience, I have created my own template for organizing the code in each file.
(function(){
'use strict';
// variables declaration and initialization
// functions declaration
// another variables initialization
// global events subscribing
// global API declaration
})();
This is a sample module to monitor any information and store this information in localStorage
(function(){
'use strict';
// variables declaration and initialization
var data = localStorage.hasOwnProperty('data') ? JSON.parse(localStorage.data) : {},
startTime;
// functions declaration
function updateField(key, value){
if(!data.hasOwnProperty(key)){
data[key] = 0;
}
data[key] += value;
}
function saveData(){
localStorage.data = JSON.stringify(data);
}
// another variables initialization
if(data.hasOwnProperty('timer')){
updateField('visit', 1);
}
// global events subscribing
document.addEventListener('customeventstart', function(event){
startTime = event.timeStamp;
});
document.addEventListener('customeventend', function(event){
updateField('timer', event.timeStamp - startTime);
});
document.addEventListener('anotherevent', saveData);
// global API declaration
window.monitor = {
save: saveData,
update: updateField
};
})();
I hope this template will be useful for someone.