Confusion on how to work with module pattern

revealing module pattern example
javascript module pattern
revealing module pattern es6
module pattern vs revealing module pattern
javascript design patterns
function module pattern
javascript revealing module pattern constructor
javascript module pattern inheritance

I am confused on how to work with module pattern (and design patterns in general) in JavaScript.

I already wrote some functioning code in my application using module pattern that does what I want to, but it doesn't seem to be very modular to me, and I keep having this feeling that I am doing it wrong. I didn't manage to find any concrete and complete application example with any design pattern.

Here is how I work with it :

Let's say I have forms in my application that I'll use for different modules (post a thread, reply to a thread, comment the guests book), with some JavaScript I'll give users some functionalities, as such as popping a smiley bubble and handling insertion of them in my forms, sending data posts to my server code to return the HTML code in order to add the message without reloading the page, I'll do something like that:

    let Form = function (selector_form, selector_textarea, selector_emoticonsButton, selector_postButton) {

      let form, textarea, emoticonsButton, postButton;
      let emoticonsBubble = new EmoticonsBubble()

      return {
        selectors: function () {
          return {
            form: function () { return selector_form },
            sendButton: function () { return selector_sendButton }
          }
        }

        setElements: function (obj) {
          form = $(obj).get(0);
          textarea = $(form).find(selector_textarea).get(0);
          emoticonsButton = $(form).find(emoticonsButton).get(0);
          postButton = $(form).find(selector_postButton).get(0);

          emoticonsBubble.setElements(form, emoticonsButton);
        },

        get: function () {
          return {
            form: function () { return form },
            //...
            emoticonsBubble: function () { return emoticonsBubble }
          }
        },

        post: function (moduleId, callback) {
          $.ajax({
          //parameters
          }).done(function (data) {
            callback(data);
          });
        }
      }
    }

    let EmoticonsBubble = function () {

      let thisContainerToAppendTo, thisTextarea;

      return {
        setElements: function (container, textarea) {
          thisContainerToAppendTo = container;
          thisTextarea = textarea;
        },

        pop: function () {
          this.ajax().pop(function (data) {
            $(thisContainerToAppendTo).append(data);
          });
        }

        insert: function (emoticon) {
          $(thisTextarea).append(emoticon);
        },

        ajax: function () {
          return {
            pop: function (callback) {
              $.ajax({
              //parameters
              }).done(function (data) {
                callback(data);
              });
            }
          }
        }
      }
    }

    // Events part

    let form = new Form('#threadForm', '.textarea', 'button[name="emoticons"]', 'button[name="send"]');
    let emoticonsBubble = form.get().emoticonsBubble();

    $(form.selectors().form()).on('click', function (e) {
      form.setElements(this);
    });

    $(form.selectors().sendButton()).on('click', function (e) {
      let moduleId = // retrieve module id, if it belongs to guests book, thread creation module or reply module
      form.post(moduleId, function (data) {
        // append data to something
      });
    });

    // etc for emoticons handling

The fact that I have to rewrite the event part for every different form I have in my application while keeping everything the same but variables name, annoys me a lot.

Could you guys tell me how you would handle those functionalities and what may be wrong with my way of coding?

Confused about javascript module pattern implementation , Lots of libraries use these patterns. I prefer CommonJS and it's very simple. You have a file which represents a module and which has 3 additional predefined� The Module Pattern is what we’d call a “design pattern,”and it’s extremely useful for a vast amount of reasons. My main attraction to the Module Pattern (and its variant, the Revealing Module Pattern) is it makes scoping a breeze and doesn’t overcomplicate program design.

The repetition in your code basically comes from the selection of elements and their helpers, and that can easily be abstracted into a function:

  function Elements(selectors, children, options) {
    let elements = { ...children };

    return {
      selectors, 
      elements,
      setElements(obj) {                
        for(const [name, selector] of Object.entries(selectors)) 
           elements[name] = $(obj).find(selector).get(0);
        for(const child of Object.values(child))
           child.parent && child.parent(this, obj);
       },
       ...options
    }
 }

That can then be used as:

  function Form(form, textarea, emoticonsButton, postButton) {
     const emoticonsBubble = EmoticonsBubble();

     return Elements({ form, textarea, emoticonButtons }, { emoticonsBubble }, {
       post() {
         //...
       }
    });
 }

 function EmoticonsBubble() {
   return Elements({ /*...*/ }, {}, {
      parent(parent, obj) {
        this.setElements(parent);
      }
   });
 }

But you are basically reinventing a lot of wheels here, have you thought about using one of the MVCs that are out there (React, Vue, ...) ?

Using the Revealing Module Pattern in Javascript � GitHub, The Revealing Module pattern is a design pattern for Javascript applications that floating around, polluting our environment and causing all sorts of confusion. It just means that we call (invoke) this function as soon as the file is run� The Module Pattern is one of the most common design patterns used in JavaScript and for good reason. The module pattern is easy to use and creates encapsulation of our code. Modules are commonly used as singleton style objects where only one instance exists. The Module Pattern is great for services and testing/TDD.

Ok the boilerplate for some common tasks that you have in the event part is driving you crazy right ?

So checking your code you can fix them in many ways.

A. Encapsulate your code in real modules I mean this.

const Form = (function(/*receive here dependencies as arguments */){
  // your code module goes here 
})(/*inject dependencies here to module*/);

B. You can create a event pattern module, to drive your internal and externals events for module.

C. You know what are the listener that the module needs , so apply them into your module.

That way should be more reusable than now

Why I don't love JavaScript's Module Pattern, The Module Pattern is the use of closures to create, in essence, It also allows me to inspect things to make sure they're working as they There may also be some confusion in what you think the module pattern does. I would like to know if the module pattern or Constructor/protoType pattern is more applicable to my work. Basically I am using unobtrusive javascript -- the HTML document has a reference to the .js file. My understanding of the module pattern: call an INIT method (which is basically a public method i can create and return using the module pattern)

JavaScript's Module and Revealing Module Patterns, In JavaScript, the module pattern is one of the most used patterns for (global variables are a source of bugs and confusion and should be avoided). By exposing what is meant to be for the public use as an API to other� The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.

JavaScript Module Pattern: In-Depth, The module pattern is a common JavaScript coding pattern. Lets work through them one-by-one, continuing with our module named MODULE . Although I am confused, whats the difference between these two as far as� The Revealing Module pattern is a design pattern for Javascript applications that elegantly solves this problem. The central principle of the Revealing Module pattern is that all functionality and variables should be hidden unless deliberately exposed.

Module Pattern in JavaScript shall allow user to return a Object from , We do not have repetative use of "this" and "Prototype" keywords, hence creating less confusion. Module Pattern offer us following Benefits: 1) Module Pattern� The module pattern can be implemented using a specialization of the singleton pattern. However, other design patterns may be applied and combined, in the same class. This pattern can be used as a decorator, a flyweight, or an adapter. Module as a design pattern. The Module pattern can be considered a creational pattern and a structural pattern

Comments
  • You are confusing (understandably) the well-known JavaScript Module Pattern, which I don't see you using anywhere in this code, with the code that goes into the module.
  • Am I not? I have private variables and public methods... I thought this was the module pattern, it looks a lot like the code showed in the linked you sent me. I am definitly missing something here
  • Nope. Setting up functions to have private vs. public members is not the module pattern. The module pattern would mean that you surround all of the code for a particular module with (function(){ ... module code here...})() and within the module, you would expose a single namespace as the access point for the module. You aren't doing that anywhere in this code. Form and EmoticonsBubble are global variable.
  • ... I'd say that the module pattern is generally a thing od tze past though, nowadays one uses webpack to bundle real modules.
  • @JonasWilms True, but that doesn't change the fact that there is a well-known JavaScript pattern called the Module Pattern, and that pattern isn't going away anytime soon. Also, WebPack is just one of many ways to implement modules of code.
  • Thanks for those clarifications, I understand module pattern better. Though, I am still a bit confused. If I want to use my EmoticonsBubble object in my Form object, do I have to write a new module for the EmoticonsBubble (so I can use it in another module) and then pass it to my Form object arguments in the global scope ? Like this let bubble = new myCustomAPI.EmoticonsBubble(arg...); let myForm = new myCustomAPI.Form(bubble, arg, arg, arg); ? Does the events part belongs to the module scope? I guess so, so it allows me to write it only once
  • @Snyte Here's why it's called the Module Pattern - - it's up to you. You decide what objects & functionality comprise a "module". You could set up EmoticonsBubble as a separate object within the myCustomAPI module and instantiate it separate from Form or you could make a generateEmoticonsBubble method of the Form object that returns a new object (ie.after instantiating a Form.... myForm.generateEmoticonsBubble()). If you felt like you might want the EmoticonsBubble object apart from a Form, you could make an entirely new module (API) for it. It's entirely up to you.
  • @Snyte Just to clarify, your last question now gets us into the realm of "coupling". In OOP, objects that are "loosely coupled" make for less brittle and more flexible designs. Examples of tight-coupling (and brittle solutions) include inheritance patterns. Examples of loose-coupling (and flexible solutions) are object composition. These two approaches are often termed as "is-a" (inheritance) and "has-a" (composition) relationships. To enable composition, we pass objects to other objects for them to use.
  • Ok, I get it. I will try to work with that, things are clearer to me. Thank you for those explanations, if you have some useful links about inheritance vs composition approaches for more informations, I am interested
  • @Snyte I'd start with loose coupling and then inheritance vs. composition.