Module Pattern

Recap: Objects

Recap: Functions

We've seen the two ways to declare a function in JavaScript:

  1. Function Declaration

    function doSomething() {
      // do something in here
    }
  2. Variable Assignment

    var doSomething = function() {
      // do something in here
    };
doSomething();                 // call the function
anotherFunction(doSomething);  // pass it into another function

Recap: Using Objects to Organize Code

var cocktails = {};

cocktails.create = {

  init: function() {
    $("#create").click(cocktails.create.submitForm);
  },

  getDataFromForm: function () {
    // returns an object containing the form data
  },

  submitForm: function() {
    var data = cocktails.create.getDataFromForm();
    // send the Ajax request to the server
  }
};

Recap: Immediately-Invoked Functions

What is the type of maxLength here?

var maxLength = function() {
  return 255;
};
alert(typeof maxLength); // will display "function"
alert(maxLength()); // will display "255"

Recap: Immediately-Invoked Functions

What is the type of maxLength here?

var maxLength = function() {
  return 255;
}();
alert(typeof maxLength); // will display "number"

How is that different from this?

var maxLength = 255;

Using Functions to Organize Code

var cocktails = {};

cocktails.create = function() {

  return {
    init: function() {
      $("#create").click(cocktails.create.submitForm);
    },

    getDataFromForm: function () {
      // returns an object containing the form data
    },

    submitForm: function() {
      var data = cocktails.create.getDataFromForm();
      // send the Ajax request to the server
    }
  };

}();

Using Functions to Hide Code

var cocktails = {};

cocktails.create = function() {

  function getDataFromForm() {
      // returns an object containing the form data
  }

  return {
    init: function() {
      $("#create").click(cocktails.create.submitForm);
    },

    submitForm: function() {
      var data = getDataFromForm();
      // send the Ajax request to the server
    }
  };

}();
cocktails.create.init();                       // works fine
var data = cocktails.create.getDataFromForm(); // error
cocktails.create.submitForm();                 // works fine

Let's go!

https://ericdouglaspratt.com/misc/academy

/

#