Waitire Colline
Waitire Colline

Reputation: 572

Uncaught ReferenceError: Alert is not defined in javascript

I am getting a "referenceError: Alert is not defined" when I click on the "OK" button of the dialog. The code works fine as expected when I call "render" function from the same file. Issues of reference error come up when I export "Alert" and I call "render" function from a different file. I wanted it to reusable but calling it in different files. I need some help. Here is my code snippets.

//dialogs.js
function CustomAlert(){

this.render = function(dialog){
    let winW = window.innerWidth;
    let winH = window.innerHeight;
    let dialogoverlay = document.getElementById('dialogoverlay');
    let dialogbox = document.getElementById('dialogbox');
    dialogoverlay.style.display = 'block';
    dialogoverlay.style.height = winH+'px';
    dialogbox.style.left = (winW/2) - (550 * .5)+'px';
    dialogbox.style.top = '100px';
    dialogbox.style.display = 'block';
    document.getElementById('dialogboxhead').innerHTML = 'Acknowledge this message';
    document.getElementById('dialogboxbody').innerHTML = dialog;
    document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
};

this.ok = function(){
    document.getElementById('dialogbox').style.display = 'none';
    document.getElementById('dialogoverlay').style.display = 'none';
};

}
export let Alert = new CustomAlert();



  //user.js
  import {Alert} from './dialogs.js';
  .
  .
  .
  .catch(error => {
        console.log('Failure', error);
        Alert.render('Something wrong happened, Please try again.');
    });


    //signup.html
     <script src="js/dialogs.js" type="module"></script>
     <script src="js/user.js" type="module"></script>

Upvotes: 1

Views: 9097

Answers (1)

Felix Kling
Felix Kling

Reputation: 816482

Inline event handlers are evaluated in global scope. Since you are using modules, every variable defined in the module is module scoped. The simplest solution would be to create a global Alert variable:

export let Alert = new CustomAlert();
window.Alert = Alert;

The right solution would be to not use HTML and inline event handlers but create the button via DOM methods and bind a proper function which closes over the module scope and has access to Alert:

const button = document.createElement('button');
button.addEventListener('click', () => Alert.ok());
document.getElementById('dialogboxfoot').appendChild(button);

Upvotes: 2

Related Questions