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';
How do I call the
loadDefault()
method from Module A into theaddNewPosts()
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.