According to my reasearch which I was doing in past few months I got to some conclusions on how to structure your application for best code reusability.
Several patterns come to my mind, Module, Namespace, immediate functions, returning objects, using subobjects, using capitalized letters for functions/variables as "Constants", function scope and making accessor methods, JS constructors, using Yuidoc and Jasmine for better code quality.
Download the code from here: https://github.com/bluePlayer/practices/tree/master/AppStructure
Here is roughly what I am thinking about:
var externalJSLibrary = {},
jquery = {},
extJS = {},
expressJS;
window.APP = window.APP || (function (wdo, lib1, lib2, lib3) {'use strict';
var version = "1.0.0",
config = {},
parent = null,
jqueryObj = lib1,
extJSObj = lib2,
expressJsObj = lib3,
windowDocumentObject = wdo,
MY_APP_NAME = "MyJSApplication",
MY_EXCEPTION_MESSAGE = "My exception message",
MY_APP_CONSTANT = "some message";
return {
Exceptions: {
MyFirstException: function () {
return {
message: MY_EXCEPTION_MESSAGE,
name: "MyFirstException"
};
}
},
Constants: {
MY_APP_NAME: function () {
return MY_APP_NAME;
},
MY_APP_CONSTANT: function () {
return MY_APP_CONSTANT;
}
},
Events: {
keyDownEvent: function (event) {
// do some stuff when some key is pressed down on 'keydown' event.
},
keyUpEvent: function (event) {
// do some stuff when some key is released on 'keyup' event
},
keyPressEvent: function (event) {
// do some stuff when 'keypress' event was detected
}
},
initApp: function (someObject, config) {
var i;
for (i in someObject) {
if (someObject[i] !== null && typeof someObject[i] === 'object') {
if (someObject[i].hasOwnProperty('init')) {
someObject[i].init(config);
}
parent.initApp(someObject[i], config);
}
}
},
namespace: function (nsString, newObjectDefinition) {
var parts = nsString.split('.'),
helperObject = {},
that = this,
i = 0,
field = {};
if (parts[0] === that.Constants.MY_APP_NAME()) {
parts = parts.slice(1);
}
for (i = 0; i < parts.length; i += 1) {
if (that[parts[i]] === undefined) {
for (field in newObjectDefinition) {
if (newObjectDefinition.hasOwnProperty(field)) {
helperObject[field] = newObjectDefinition[field];
}
}
that[parts[i]] = helperObject;
}
that = that[parts[i]];
}
return that;
},
customFunction: function (a, b) {
if (b < 0) {
throw new parent.Exceptions.MyFirstException();
} else {
return 0;// do some stuff with a and b
}
},
doSomeStuffWithJquery: function (someUrl) {
jqueryObj.ajax({
url: someUrl,
xhrFields: {
withCredentials: true
}
});
},
doSomeStuffWithExtJS: function () {
extJSObj.drawGraph();
},
doSomeStuffWithExpressJS: function () {
expressJsObj.connectWithNodeJS();
},
init: function (configObject) {
config = configObject;
parent = this;
parent.initApp(parent, config);
}
};
}(window.document, jquery, extJS, expressJS));
window.APP.namespace('MySubObject', (function (lib) {'use strict';
var config = {},
parent = null,
someLibrary = lib,
MY_CONSTANT = "my constant",
MY_EXCEPTION = "my exception";
return {
Exceptions: {
MyNewException: function () {
return {
message: MY_EXCEPTION,
name: "MyNewException"
};
}
},
Constants: {
MY_CONSTANT: function () {
return MY_CONSTANT;
}
},
name: "MySubObject",
myCustomFunction: function () {
// do some stuff
},
init: function (configObj) {
config = configObj;
parent = this;
}
};
}(externalJSLibrary)));
window.document.addEventListener("DOMContentLoaded", function (event) {'use strict';
var myApp = window.APP;
myApp.init({
"event": event,
otherConfig: {}
});
window.document.addEventListener('keydown', myApp.Events.keyDownEvent);
window.document.addEventListener('keyup', myApp.Events.keyUpEvent);
window.document.addEventListener('keypress', myApp.Events.keyPressEvent);
});
Programming and tech blog. PHP, Java, Android, JavaScript, HTML5
Showing posts with label jslint. Show all posts
Showing posts with label jslint. Show all posts
Thursday, February 26, 2015
Friday, November 14, 2014
"JavaScript: The Good Parts" - book review
In this post I'll explain my thoughts on "JavaScript: The Good Parts" written by Douglas Crockford. It is fairly old book written in 2008 but still does the good job of teaching you what to use and what not to use from JavaScript. As the author says, this book has lot of information packed in about 150 pages, which means you have to read at least twice each chapter. Yes I passed each chapter twice and also spent some time writing the code from the book in Firefox/Firebug just to see how it goes. I think more examples to practice would be much better for the book as it lacks them. But in the end you would certainly need to read another book to learn how to code proper JavaScript modules, patterns, etc... I am planning to read another book because this one is not enough to get you going with JS. My recomendation for next book would be this one: "JavaScript Patterns" - by Stoyan Stefanov, it has about 240 pages which is enough.
The book is structured in 10 chapters and with 5 appendices, A-E. My suggestion is to read all chapters includding the appendices. Appendix D is just the railway diagrams, so you may skip it.
Chapters:
The book is structured in 10 chapters and with 5 appendices, A-E. My suggestion is to read all chapters includding the appendices. Appendix D is just the railway diagrams, so you may skip it.
Chapters:
- Good Parts. This chapter contains basic info about JS and how to set up testing ground for other code examples in the book. Don't skip it.
- Grammar. Contains basic information about reserved keywords in JS, data types, expressions, functions etc...
- Objects. Explain how to work with Objects in JavaScript, how to create new object, how to retrieve infrormation from object, object prototype, reflection, enumeration, delete operator, etc...
- Functions. Dives into JavaScript function basics. How to create new function, how to invoke a function, this and arguments objects of a function, its connection with objects. Each function is an object so you can add a function to its prototype. Function scope, closure, function modules, cascade (builder pattern), curry and memoization.
- Ineritance. Inheritance types, implementing standard OOP in JS (pseudoclassical) inheritance, prototypal and functional inheritance. Very important chapter, don't skip it.
- Arrays. Array basics, length property, useful array methods, delete operator, enumeration, etc...
- Regular Expressions. Dives into JS regular expressions, what are they and how to use them. Couple of basic rules how do RE work. Very useful thing, especially when processing strings.
- Methods. This chapter explains implemented methods that come with JavaScript itself. You may want to skip this chapter but it would be helpful if you read it.
- Style. This chapter explains some techniques how to write error prone JavaScrtipt code. My suggestion is to not skip this chapter.
- Beautiful features. Read this chapter to learn what are the best parts of JavaScript that you should use. Functions as a first class object, Dynamic objects with prototypal inheritance and Object litrals and array literals.
- Appendix A. Awful Parts. Explains all of the worse parts in JS and how to avoid them.Global variables, scope, semicolon insertion, reserved words, unicode, typeof operator, parseInt function, + operator, floating point, NaN, phony arrays, falsy values, hasOwnProperty function and Object.
- Appendix B. Bad parts. Things you can live with but still should avoid. == vs === operators, with statement, eval function, continue statement, switch fall trough, block-less statements, ++ and -- operators vs += and -= operators, bitwise operators, function statement vs function expression, typed wrappers, new operator, void keyword.
- Appendix C. JSLint. An online tool build by Douglas himself. Use it whenever possible to debug your JS code. You may find this tool also useful, http://jsbeautifier.org/
- Appendix D. Syntax Diagrams. If you are beginner at programming, these railway diagrams will help you get going.
- Appendix E. JSON. Explains what is JSON, JSON syntax, how to use it securely and a complete script of JSON parser in JavaScript.
Labels:
basic,
book,
book review,
douglas crockford,
javascript,
jsbeautifier,
jslint,
JSON,
patterns,
the good parts
Subscribe to:
Posts (Atom)