I am working on Single Page Architecture (SPA) Web application. I am have implemented functionality to dynamically load different pages of application.
This is what my spa.js looks like
var spa = {
init: async () => {
await import('./page.js')
spa.data['page'].apply()
},
register: (page, data) => {
spa.data[page] = data
},
data: {},
}
window.onload = () => {
spa.init()
}
And this is what my page.js looks like
const pageData = {
apply: () => {
document.body.innerHTML = getMSG()
}
}
function getMSG() {
return "hello message!"
}
spa.register('page', pageData)
The working process explained:
- Initially spa.js loads. spa.data is empty
- It initiates spa.init(), which loads page.js
- page.js registers its data to spa variable
- Now control jumps back at spa.js and from spa.data for page, it will execute apply()
This works fine. But here's a strange thing!
The apply() method has access to bare getMSG(), but when I try to execute getMSG() it via browser's developer console I get ReferenceError implying that getMSG() is not defined at all! Same goes with our pageData
Here is the hosted heroku app, you can try - dyn-import
Although it is very good as I don't have to worry about clashing functions in different files, I want to know how this is happening.
Can someone explain how can I access methods and variables defined in page.js. I am aware about exports, but it is somehow possible without exports!
await import('./page.js').then()
is very strange. Either youawait something()
, or you go Promise-style withsomething().then()
. But not both – Silva