Modularization

The important thing you should know as a frontend developer

Created by Howard Zuo / @leftstick

What is Modularization

“A programming style that breaks down program functions into modules, each of which accomplishes one function and contains all the source code and variables needed to accomplish that function”

Modularity

Generally a modular application is composed of a set of highly decoupled, distinct pieces of functionality stored in modules

As you probably know, loose coupling facilitates easier maintainability of apps by removing dependencies where possible. When this is implemented efficiently, its quite easy to see how changes to one part of a system may affect another

Why Modularization?

deprecated
deprecated
No Way
“We humans are limited when it comes to grasping complex problems all at once. However, we are gifted in the ability to decompose a complex problem into a (possibly very large) number of individual problems that are not too complex in order to tackle the big problem”

This is fundamentally what drives answers like "reuse", "separation of concerns", "easier maintenance"

Modularity Flavors

Anonymous Closures


var loginModule = (function() {
    'use strict';

    var module = {};
    module.login = function(userName, userPassword) {
        console.log('login implementation omitted');
    };

    module.logout = function() {
        console.log('logout implementation omitted');
    };

    return module;
})();

Anonymous Closures With Global Injected


(function(global) {
    'use strict';

    var module = {};
    module.login = function(userName, userPassword) {
        console.log('rest of login implementation is omitted');
    };

    module.logout = function() {
        console.log('logout implementation omitted');
    };

    global.loginModule = module;

})(this);

Why Modular Standard

  • Avoid naming conflict in global
  • Separation of dependency concerns
  • File concatenation for production
  • Handy tools are ready for use
  • Complete documentation
  • Easy to learn, easy to share

Define Module In AMD


define([module_id,] [dependencies], function (){
    'use strict';

    //Put the module definition here
});
UserModel.js

define([], function() {
    'use strict';

    var User = function(){
        this.data = {};
    };

    User.prototype.set = function(key, value){
        this.data[key] = value;
    };

    User.prototype.get = function(key){
        return this.data[key];
    };

    User.prototype.toString = function(){
        return JSON.stringify(this.data);
    };

    return User;

});
UserService.js

define(['./UserModel', 'jquery'], function(User, $) {
    'use strict';

    var service = {};

    service.fetchUsers = function(){
        return $.ajax({
                url: '/users',
                method: 'method',
                dataType: 'json',
                converters: {
                    "text json": function(raw){
                        var data = JSON.parse(raw);
                        var users = data.map(function(d){
                            var user = new User();
                            user.set('name', d.name);
                            user.set('age', d.age);
                            return user;
                        });
                        return users;
                    }
                }
            });
    };

    return service;

});
Controller.js

define(['jquery', 'lodash', './logic/UserService',  './logic/usersTpl.html'], function($, _, UserService, usersTpl){
    'use strict';

    UserService.fetchUsers()
    .done(function(users){
        var html = _.template(usersTpl)({users: users});
        $('.usersList').empty();
        $('.usersList').append(html);
    });

});

Play Demo


git clone https://github.com/leftstick/why-modularization.git
cd why-modularization
git checkout amd
npm install
npm start

Go open http://localhost:8080 to view the demo

Go and Check the source code to see how they work

Define Module In CommonJS


'use strict';

var sample = function(){};

module.exports = sample;
UserModel.js

'use strict';

var User = function() {
    this.data = {};
};

User.prototype.set = function(key, value) {
    this.data[key] = value;
};

User.prototype.get = function(key) {
    return this.data[key];
};

User.prototype.toString = function() {
    return JSON.stringify(this.data);
};

module.exports = User;
UserService.js

'use strict';

var User = require('./UserModel');
var $ = require('jquery');

var service = {};

service.fetchUsers = function() {
    return $.ajax({
        url: '/mock/users.json',
        method: 'GET',
        dataType: 'json',
        converters: {
            'text json': function(raw) {
                var data = JSON.parse(raw);
                var users = data.map(function(d) {
                    var user = new User();
                    user.set('name', d.name);
                    user.set('age', d.age);
                    return user;
                });
                return users;
            }
        }
    });
};

module.exports = service;
Controller.js

'use strict';

require('bootstrap/dist/css/bootstrap.css');
var $ = require('jquery');
var _ = require('lodash');
var UserService = require('./logic/UserService');
var usersTpl = require('./logic/usersTpl.html');

UserService.fetchUsers()
    .done(function(users) {
        var html = _.template(usersTpl)({users: users});
        $('.usersList').empty();
        $('.usersList').append(html);
        $('#info').toggleClass('alert-warning').toggleClass('alert-success').html('User List loaded');
    });

Play Demo


git clone https://github.com/leftstick/why-modularization.git
cd why-modularization
git checkout commonjs
npm install
npm start

Go open http://localhost:8080 to view the demo

Go and Check the source code to see how they work

Define Module In ES6


'use strict';

var sum = (x, y) => {
    return x + y;
};

export default sum;
UserModel.js

'use strict';

var User = function() {
    this.data = {};
};

User.prototype.set = function(key, value) {
    this.data[key] = value;
};

User.prototype.get = function(key) {
    return this.data[key];
};

User.prototype.toString = function() {
    return JSON.stringify(this.data);
};

export default User;
UserService.js

'use strict';

import $ from 'jquery';
import User from './UserModel';

var service = {};

service.fetchUsers = function() {
    return $.ajax({
        url: '/mock/users.json',
        method: 'GET',
        dataType: 'json',
        converters: {
            'text json': function(raw) {
                var data = JSON.parse(raw);
                var users = data.map(function(d) {
                    var user = new User();
                    user.set('name', d.name);
                    user.set('age', d.age);
                    return user;
                });
                return users;
            }
        }
    });
};

export default service;
Controller.js

'use strict';

import 'bootstrap/dist/css/bootstrap.css';
import $ from 'jquery';
import _ from 'lodash';
import UserService from './logic/UserService';
import usersTpl from './logic/usersTpl.html';

UserService.fetchUsers()
    .done(function(users) {
        var html = _.template(usersTpl)({users: users});
        $('.usersList').empty();
        $('.usersList').append(html);
        $('#info').toggleClass('alert-warning').toggleClass('alert-success').html('User List loaded');
    });

Play Demo


git clone https://github.com/leftstick/why-modularization.git
cd why-modularization
git checkout es6
npm install
npm start

Go open http://localhost:8080 to view the demo

Go and Check the source code to see how they work

Advertisement

Thanks

Welcome give a try of ES6

- Source Code