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

Patrioticcow picture Patrioticcow · Aug 20, 2012 · Viewed 24.6k times · Source

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

Answer

Jack Franklin picture Jack Franklin · Aug 20, 2012

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.