Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use the javascript module pattern in a real example?

I am trying to understand the JavaScript Module Pattern. I've seen examples of what it should look like, but I don't understand how to use it.

For example, a few things are happening here:

$('input#share').on("click", function() {

    $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" />');

    var message = $(".wallmessage").val();

    if (message == ""){
        $("#messageempty").jmNotify();
        $('.remove_loading').remove();
    } else {
        addMessage(message);
    }

    return false;
});


function addMessage(message)
{
    $.ajax({
        url: '/test',
        type: 'POST',
        dataType: "json",
        data: {'message' : message},
        success: function(data) {
                ...
        },
        error: function() {
            ...
        }
    });
}

How can I use the above example with:

var myTest = function() {
    var selectId;
    function addMessage () {
        // ...
    }
    return { // public interface
        publicMethod1: function () {
            // all private members are accesible here
        }
    };
};
var start = myTest();

Where do I add the click event, declare my vars, add the addMessage function with the ajax call. and call the addMessage function? Do i have to wrap everything in $(document).ready(function()?

Can anyone shed some light on this for me?

Thanks

like image 268
Patrioticcow Avatar asked Aug 20 '12 17:08

Patrioticcow


People also ask

Why is it important to use the module pattern in JavaScript?

Maintainability: Module Patterns enable better maintainability since all the related code can be encapsulated inside a single logical block. These logically independent blocks are relatively easier to update. Reusability: We single unit of code can be reused across the entire application.

When would you use the revealing module pattern?

Revealing module pattern is a design pattern, which let you organise your javascript code in modules, and gives better code structure. It gives you power to create public/private variables/methods (using closure), and avoids polluting global scope (If you know how to avoid that).


4 Answers

This is quite an opinionated subject, but I'd do it (without entirely knowing your full app and what it does), somewhat like so:

var myApp = (function() {

  var someElement = $("#foo"); //some element I know I'll use lots

  var addMessage = function(message) {
    $.ajax({
      url: '/test',
      type: 'POST',
      dataType: "json",
      data: {'message' : message},
      success: function(data) {
              ...
      },
      error: function() {
          ...
      }
    });
  };

  var inputClick = function(event) {
    event.preventDefault();
    //depending on if you'll reuse these selectors throughout the app I might have these as variables
    $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" />');

    var message = $(".wallmessage").val();

    if (message == ""){
      $("#messageempty").jmNotify();
      $('.remove_loading').remove();
    } else {
      addMessage(message);
    }
  };

  var bindFunctions = function() {
    $("input#share").on("click", inputClick)
  };

  var init = function() {
    bindFunctions();
  };

  return {
    // EDIT: 27/12/16 - need to return init for 'usage' example to work
    init: init,
    addMessage: addMessage
    //anything else you want available
    //through myApp.function()
    //or expose variables here too
  };


})();

//usage

myApp.init();

Your original code for the pattern is wrong, the function has to have () at the very end, to make it a function that is immediately invoked, and then executes, exposing anything through the return statement.

You may wish to differ slightly from what I've done, it's only a basic idea but I hope it might get you started.

Someone a while back asked a question relating to this pattern and I answered it explaining why we use (function() {})(); and how the return statement works in that context, if you're slightly confused by it that might be worth reading too.

like image 64
Jack Franklin Avatar answered Oct 05 '22 22:10

Jack Franklin


The revealing module pattern is used like this:

var moduleName = (function () {
    var privateVariable = 'private';

    var privateMethod = function () {
        alert('this is private');
    };

    // this is the "revealed" part of the module
    return { 
        publicVariable: 'public',
        publicMethod: function () {
            alert('this is public');
        }
    };
}());

You can also define the public variables/methods as privates and then expose a reference to them, making them public. This is a matter of preference.

In your example, if you wanted addMessage to be part of the module, you would do it like this:

var moduleName = (function () {
    // this becomes public due to the reference exposure in the return below
    var addMessage = function () {
        // do whatever
    };

    // this is the "revealed" part of the module
    return { 
        addMessage: addMessage
    };
}());

moduleName.addMessage();
like image 26
jbabey Avatar answered Oct 05 '22 22:10

jbabey


Unlike JAVA, Javascript does not have the concept of private and public on properties or on methods. Let’s create an object called person which has 2 properties firstName and lastName, and also create 2 functions which will be getters for our properties. In Javascript we can create functions as properties of objects & those functions are accessible like any other property anywhere.

var person={
  "firstName":"Anoop",
  "lastName":"Rai",
  "getFirstName":function(){
    return this.firstName;
  },
  "getLastName":function(){
    return this.lastName;
  }
};
console.log(person.getFirstName());
console.log(person.firstName);

As expected above codes 11 prints Anoop and Anoop. Hmmm, that’s not good for object oriented programming. Well, we successfully implemented getters and so we should also have setters that should be of public scope and properties should be marked as private scope (what??? these private and public concept belongs to JAVA, C++ like languages). Our intentions are good, lets apply concepts specific to Javascript. We don’t want to do person.firstName, we want the prevent the access of the property directly. In languages like JAVA because of private and public we achieved the controlled acccess of properties, but in Javascript everything is public.

Javascript uses concept of closures to implement things like private & public. This pattern is called Module Pattern. That is, hiding variables from public access. In order to implement scopes, wrap your codes in a function (remember, scopes are implemented via functions in Javascript).

function createPerson(){
  var returnObj={
    "firstName":"Anoop",
    "lastName":"Rai",
    "getFirstName":function(){
      return this.firstName;
    },
    "getLastName":function(){
      return this.lastName;
    }
  };
  return returnObj;
}
var person=createPerson();
console.log(person.getFirstName());
console.log(person.firstName);

Now also above lines prints Anoop and Anoop. Still no success. As long as properties are tied to the object it will be accessed directly. Let’s untie it. Instead of properties we make variables of function scope (closure variables).

function createPerson(){
  var firstName="Anoop";
  var lastName="Rai";
  var returnObj={
    "getFirstName":function(){
      return firstName;
    },
    "getLastName":function(){
      return lastName;
    }
  };
  return returnObj;
}
var person=createPerson();
console.log(person.getFirstName());
console.log(person.firstName);

Now above lines prints Anoop and undefined. How does this happen? Because of closures, when the functions getFirstName and getLastName was created the functions had the whole scope chain or say pointers to the relevant variables i.e. firstName and lastName. The object returnObj does not remember the variabes but the function objects remembers, because of closures. Looks like we achieved what we wanted to, but one thing is left and that is setters for the controlled access of firstName and lastName. Let’s implement setters.

function createPerson(){
  var firstName="Anoop";
  var lastName="Rai";
  var returnObj={
    "getFirstName":function(){
      return firstName;
    },
    "getLastName":function(){
      return lastName;
    },
    "setFirstName":function(name){
      return firstName=name;
    },
    "setLastName":function(name){
      return lastName=name;
    }
  };
  return returnObj;
}
var person=createPerson();
console.log(person.getFirstName());
person.setFirstName("Kumar");
console.log(person.getFirstName());

We successfully modified firstName but in a controlled manner.

http://jkoder.com/the-module-pattern-javascript-way-of-hiding-data-in-objects-from-public-access/

like image 30
Anoop Rai Avatar answered Oct 05 '22 22:10

Anoop Rai


The idea is to cut down the visibility from outside world and better code management by dividing your code into segments/modules.Check this out if you want to see a really good usage of modular design pattern and some way of how we can get benefit from it.
http://learn.jquery.com/code-organization/concepts/

like image 41
kta Avatar answered Oct 05 '22 22:10

kta