1

I have a bunch of js code that I'm trying to wrap using the module pattern:

(function(){

function closeClicked(closeButton)
{
//do some stuff
}
//some more js code

}());

The html caller is defined like this:

<button type="button" onclick="closeClicked(this)">
<span aria-hidden="true">×</span></button>

The code injects some html into an element on the page and the button within the html calls the js function. This works as expected but the function is not found when all of the code is wrapped as a module. Do I need to define or call the function differently when this code is wrapped as a module?

1
  • 1
    You don't have access to closeClicked outside the anonymous function. There are two options: either add an event listener in JavaScript, not in HTML or expose closeClicked in global scope (I do not advice doing that). Commented Jul 26, 2016 at 21:27

1 Answer 1

0

This is by design. Variables in a closure are not accessible outside the closure.

In the module pattern you expose a module which contains your functionality. In this case, it would look something like this:

var myModule = (function(){

    function closeClicked(closeButton)
    {
    //do some stuff
    }

    //some more js code

    return {
        closeClicked: closeClicked
    }
}());

myModule would be the object that's being returned from the outer function. And then you would reference myModule.closeClicked.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Daniel. How would I expose multiple functions on a module. Something like this although this actual code doesn't work: var TestModule = (function(){ function CloseClicked(closeButton) { alert('close clicked'); } function AnotherFunction(); { alert('another function called'); } return { CloseClicked: CloseClicked, AnotherFunction: AnotherFunction } }());
that semicolon at function AnotherFunction(); {...} should not be there. It should be function AnotherFunction() {...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.