Thursday, February 26, 2015

How to structure you JS application

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

    });

"JavaScript Patterns" - book review

Hello. In this post I will share my thoughts on a book called "JavaScript Patterns" written by Stoyan Stefanov. Published in 2010 this book in about 210 pages covers the most important patterns that you can use in JavaScript to ease you work with this language. My guess is that this book is not for beginner JavaScript programmer, but you can always read this great book by Douglas Crockford, "JavaScript: The Good Parts" as an intro to JavaScript. These two books go hand in hand. Check my other book review here: http://tunephp.blogspot.com/2014/11/javascript-good-parts-book-review.html
If you really want to learn proper JS programming read both of them, first "JS the good parts" and then "JS Patterns" and try some programming practices in Firefox/Firebug.

The book has 8 chapters and has lot of useful code snippets you can use in building your brand new JavaScript application.

  1. Intruduction. Explains basic concepts of JS, like there are no classes in JS, everything is a object including, functions, arrays, objects etc... It also notes that you can use strict ("use strict", ECMAScript 5) mode, a modification of JS that removes some of the bad parts in JS. This chapter also introduces JSLint and the Console as debugging tools. You should always check your code with JSLint.
  2. Essentials. This chapter covers one of the main drawbacks in JS, and those are global variables. It also gives some tips how to avoid using too many globals, how to use "for", "for in" loops, avoiding implied typecasting with "==" sign, number conversions with parseInt() and parseFloat(), writing proper code, indentation, writing comments and using Yuidoc and JSLint.
  3. Literals and Contructors. It covers Object literal ({}) notation, JS constructors and naming convention for them and how to avoid problems using constructors. Array literals, check for "Arrayness" (arrays are objects in JS), working with JSON, regular expressions, primitive wrappers and throwing Errors/Exceptions.
  4. Functions. Covers function decalrations vs function expressions. Variable hoisting, function scope, function callbacks, returning functions, self defining functions, immediate functions and couple of useful tricks like memoization, curry, init-time branching etc... Probably the most important chapter in the book, you must not miss it as functions are the hearth of JavaScript.
  5. Object Creaing Patterns. Some object creating patterns like namespace patters(there is a very useful function for creating a tree of subobject, you can use it in your project.), private members, how to achieve real privacy in JS, Module pattern, Sandbox patterns, static members, JS "Constants", Chaining pattern etc... This chapter gives you better idea how to structure your code so that your project doesn't have trouble in the end.
  6. Code Reuse Patterns. Classical vs Prototypal inheritance patterns. You should avoid Class inheritance in JS since it is just a "syntaxic sugar", and always use Prototypal inheritance. This chapter also mentions some useful code reuse techniques, like borrowing methods, copying properties, some Class patterns etc...
  7. Design Patterns. This chapter covers how to code basic software engineering patterns in JavaScript, probably a chapter you don't want to miss. Singleton, Factory, Iterator, Decorator, Strategy, Facade, Proxy, Mediator and Observer. 
  8. DOM and Browser Patters. Covers some tools/concepts/patterns that can be used in a browser, like how to manipulate DOM tree, event handling, long running scripts, Ajax alikes, JSNOP, combining JS scripts, minifying, Loading techniques and preloading.
 So yes, this book cover very useful features of JavaScript and how to use them in browser. If you really want to become a web dev. this is the right book for you.

There are similarities with "JavaScript: The Good Parts" in the beginning, I felt like I was reading Doug's book again, but that is ok. It has lot of code and it is well explained so my grade for it is 4.5/5. Defineitely a book you should read.

Monday, February 23, 2015

Introducing new project called ZadachiJS

In the past few weeks I have been working on a new project called ZadachiJS. It is adapted for Macedonian public and the docs are written in Macedonian using english letters. It is basically a web application that has no GUI and all output is sent to the console, ofcourse the output is in Macedonian. It contains programming practices which could be made in any programming language and it is based on a book called „Збирка Алгоритми и Програми“, од Ѓорги Јованчевски, Билјана Стојчевска и Невена Ацковска or in english, "Collection of Algorithms and Programs" written by Gyorgy Yovanchevsky, Bilyana Stoychevska and Nevena Atckovska. I couldn't find english version of it, but I could in Macedonian. Not sure if there is going to come an english version. So if you want to understand this project better learn Macedonian, because probably I won't find time to translate it in English, who knows.

Збирка Алгоритми и Програми
Збирка Алгоритми и Програми

The JavaScript part consists of one global object called Zadachi and all other stuff are inside of it.
You can browse the code here: https://github.com/bluePlayer/practices/tree/master/ZadachiJS
or check the demo here: http://jspractices-blueplayer.rhcloud.com/Zadachi and the docs here: http://jspractices-blueplayer.rhcloud.com/Zadachi/docs
Jasmine.js tests are here: http://jspractices-blueplayer.rhcloud.com/Zadachi/SpecRunner.html

Thursday, February 19, 2015

New location for JavaScript practices.

Check this link for my new page regarding JavaScript demos.

http://jspractices-blueplayer.rhcloud.com/

GitHub: https://github.com/bluePlayer/practices

Note: If some of the demos is unavailable write me on this post or an email, because openshift sets the process to idle state if the page is not accessed often.