Home > Software engineering >  Call code outside of IIFE from within IIFE
Call code outside of IIFE from within IIFE

Time:03-05

I have code that successfully calls a function in an IIFE that, in turn, references code outside of the IIFE that I can't figure out how to call.

const msgbox = (function () {
  function showMsgBox(msg) {
    const modal = document.createElement("div");
    modal.classList.add("modal");
    modal.innerHTML = `<div ><p>${msg}</p></div>`;
    document.body.appendChild(modal);
    modal.style.display = "block";
    window.onclick = function (event) {
      if (event.target === modal) {
        modal.style.display = "none";
      }
    };
  }
  return {
    showMsgBox: showMsgBox
  };
})();

  const example = document.getElementById("example");

  function changeClass() {
    if (example.getAttribute("class") === "classTwo") {
      example.classList.remove("classTwo");
      example.classList.add("classOne");
    } else {
      example.classList.add("classTwo");
      example.classList.remove("classOne");
    }
  }

  document.querySelectorAll(".change_class").forEach((item) => {
    item.addEventListener("click", function (e) {
      changeClass();
    });
  });
  
  document.querySelector(".showmsg").addEventListener("click", function (e) {
    msgbox.showMsgBox(
      'Call Function outside of IIFE=> <button >Change Class</button> (<= this button should have the same functionality as the other button)'
    );
  });

I tried putting the non-IIFE section into its own IIFE and giving it a separate namespace but that didn't work. The example above is a simplified version of my actual problem, but this encapsulates my problem more succinctly and makes it less confusing. Yes, I could make the IIFE simply a function and call it that way, but I'm trying to expand my knowledge.

Here's a link to the CodePen example I created for this: https://codepen.io/NoahBoddy/pen/PoOVMzK Hopefully, my explanation is clear. If not, I can provide more detail. Thanks!

CodePudding user response:

The button in the modal has no click handler, so it does nothing:

msgbox.showMsgBox(
   'Call Function outside of IIFE=> <button >Change Class</button> (<= this button should have the same functionality as the other button)'
);

You could either set the click handler inline:

msgbox.showMsgBox(                                        
  • Related