Home > Net >  Event listeners inside Javascript components / communicating between files
Event listeners inside Javascript components / communicating between files

Time:01-16

I am trying to organise my code into components/modules and I'm struggling to understand how to deal with event listeners and/or communicate between JS files. I will explain with a simplified example:

In this hypothetical, app.js imports all the other js file components. In app.js I call a function in nav.js to render my nav to the DOM and I add event listeners to a single button.

When the button is clicked my event handler inside nav.js picks it up and I want to somehow communicate back to app.js and tell it to call a function inside pageA.js to render the page.

I'm not sure if this is the right approach or if I'm missing a key concept to get this working. Any tips would be appreciated.

index.js

import Nav from './nav.mjs';
import PageA from './pageA.mjs';
export default class App {
    constructor() {
        this.nav = new Nav();
        this.pageA = new PageA();
        this.nav.renderNav();
    }
}

nav.js

export default class Nav {
    constructor() {
    }
    renderNav(){
        let button = document.createElement("button");
        button.innerHTML = "Page A";
        document.body.appendChild(button);
        button.addEventListener ("click", function() {
            // How do I call renderPageA() in pageA.js?
        });
    }
}

pageA.js

export default class PageA {
    constructor() {
    }
    renderPageA(){
        let pageDiv = document.createElement('div');
        document.body.appendChild(pageDiv);
    }
}

CodePudding user response:

You can pass pageA instance as a parameter in the Navs constructor.

//Nav constructor
constructor(pageA){
    this.pageA = pageA
}

//Add this to the event listener's callback:
this.pageA.renderPageA()

//index.js
this.nav = new Nav(pageA)

Note that you have to instantiate pageA before nav for this to work.

  • Related