1

I've been experimenting with Javascript's Revealing Module Pattern, but I don't quite understand if and how I can call a public method of one module into another. Suppose I have these two modules (code is simplified):

1) Module A

var lazyload = ( function() {

    function loadDefault() {
        $('.lazy').load();
    } 

    return {
        loadDefault: loadDefault
    }

})();

2) Module B

var newposts = ( function() {

    function addNewPosts() {
        $('.posts').append();
    }

});

How do I call the loadDefault() method from Module A into the addNewPosts() method from Module B? Not sure if this has anything to do with it, but maybe it's worth mentioning that I'm using Webpack, so in my main .js file I'm importing both modules as such:

import './ModuleA';
import './ModuleB'; 
grazdev
  • 1,082
  • 2
  • 15
  • 37
  • if you're using the `import` syntax to bring in functions you want to call, you'll have to `export` them in the modules: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export – worc Oct 11 '17 at 17:28

1 Answers1

1

How do I call the loadDefault() method from Module A into the addNewPosts() method from Module B?

If you were using the old-style revealing module pattern, you'd do lazyload.loadDefault(). But keep reading...

Not sure if this has anything to do with it, but maybe it's worth mentioning that I'm using Webpack, so in my main .js file I'm importing both modules as such:

import './ModuleA';
import './ModuleB'; 

Then you don't want to use the RMP. Instead, use export:

lazyload.js:

export function loadDefault() {
    $('.lazy').load();
} 

newposts.js:

import {loadDefault} from './ModuleA';

export function addNewPosts() {
    loadDefault();
    $('.posts').append();
}

Or if you want the one function you're exporting to be the default:

lazyload.js:

export default function loadDefault() {
    $('.lazy').load();
}

...and then the import is

import loadDefault from './ModuleA';

The RMP was way to work around the problem of JavaScript not having modules. Once you're using actual modules (introduced in ES2015), you don't need the RMP (for modules) anymore.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875