Digbyswift
Digbyswift

Reputation: 10410

How can I improve my javascript pattern for greater flexibility/maintainability?

Currently I load all my javascript with a pattern similar to the code below. One file would reflect a single page or component in a site. For example, if I had a contact page the associated javascript file might be:

(function () {

    $(function () {
        contactForm.init();
        locationMap.init();
    });

    var contactForm = {

        init: function () {
            ... Do form manipulation here
        }
    };

    var locationMap = {

        init: function () {
            ... Do map manipulation here
        }
    };

})();

This is fine for smaller sites but as a site grows and functionality needs to be shared across pages or certain components develop a reliance on each other (e.g. the options in the contact form might change based upon the selection location map) this pattern shows it's limitations.

My question is, how can I improve this to allow for growing complexity and reliance between modules?

Upvotes: 2

Views: 78

Answers (2)

inf3rno
inf3rno

Reputation: 26137

You should use a module loader, like requirejs or browserify. By requirejs you have to use AMD style module definitions, by browserify you have to use commonjs style module definitions. Commonjs is not compatible with browsers by default (it is for nodejs), so you have to build browser compatible js files from it (browserify does that). In your case requirejs might be a better solution (if you are not familiar with nodejs), but I suggest you read more about both.

Another possible solution is using ES6 modules. Currently you have to build by them as well, but later they will be supported by every browser I think.

Upvotes: 1

Marian Ban
Marian Ban

Reputation: 8188

Good improvement will be organizing your code in namespaces and use The Revealing Module pattern:

var contact = contact || {};
var contact.form = (function () {
    // private functions
    function privateFunction() {}        
    // public functions
    function init() {
        privateFunction()
        ... Do form manipulation here
    }

    return {
        init : init
    };
})();

but for more complex applications i suggest to look for some MVVM architecture framework (i prefer AngularJS)

Upvotes: 1

Related Questions