Question

I am implementing the Revealing Module pattern in JavaScript and having difficulty in accessing the declared variable in another script. Below is my code.

Script1:

var SomeEventHandler = (function (){

    var logSomeEvent = function(){...}
    return {
        trackEvent: logSomeEvent;
    };
})();

Script2:

SomeEventHandler.trackEvent(); // This gives me undefined error. 

In the HTML, I have added script 1 before script 2, so I wanted to know how can i access SomeEventHandler in script 2.

Was it helpful?

Solution

I noticed that you have a semicolon in your object notation. Multiple key:value properties in objects created with object-notation are separated by commas, not semicolons. Also, you don't need the separator if there is only one element. I removed the semicolon and it works fine in my testing.

var SomeEventHandler = (function (){
    var logSomeEvent = function() { console.log('Cool stuff happened!'); }
    return {
        trackEvent: logSomeEvent
    };
}());

// ...

SomeEventHandler.trackEvent(); // Cool stuff happened!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top