Saturday, August 2, 2014

Revealing Module pattern in AngularJS

If you have worked with object oriented programming you are aware that there are private and public methods and properties. But that concept completely lacks in JavaScript. Wouldn’t be nice if JavaScript also has the same private and public concepts.

Revealing Module pattern encapsulates the JavaScript classes (functions) and reduces the spaghetti code. This pattern sometimes looks like an interface. This pattern ensures that all the methods and variables are private by default until they are explicitly exposed as public.  This pattern provides a very good structure to the JavaScript code and makes it is easier to understand and use.

I will first show a javascript code that we typically use for an Angular controller and then refactor it with Revealing Module pattern.

Let’s assume that we are working on a Contact page, where user enters First Name and Last Name of a Contact and clicks save button to save the contact.

Here is the code we typically use for this scenario

angular.module('app').controller('contact', function($scope) {

    $scope.firstName = "Praval";
    $scope.lastName = "Pattam";

    $scope.save = function () {
        alert('contact saved');
    }
});

Let’s rewrite the same controller code using the Revealing Module Pattern:

angular.module('app').controller('contact', function() {

    var vm = {
        firstName: "Praval",
        lastName: 'Pattam',
        save: save
    };

    return vm;

    function save() {
        alert('contact saved');
    }
});

As you see in the above code, from the first line we know what all this controller does. This is similar to the interface we see in object oriented languages. With this pattern and ControllerAs functionality we can eliminate the $scope from our code.


This Revealing Module Pattern is my favourite pattern for structuring the JavaScript code as it provides a clean interface. For my other patterns and demos please check out my GitHub site.

No comments:

Post a Comment