I have been working on a dialog in a project and I made it into an object constructor.
function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
this.dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
this.No = this.dialog.getElementsByTagName("button")[0];
this.Yes = this.dialog.getElementsByTagName("button")[1];
var dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle.innerHTML = title;
document.getElementsByClassName("dialogCon")[0].style.display = "flex";
noClicked();
yesClicked();
}
<div class="dialogCon">
<div class="dialog">
<h1></h1>
<button type="button">No</button>
<button type="button">Yes</button>
</div>
</div>
The problem is that when I want to access "this.no" or "this.yes" I keep getting Cannot read property 'No' of undefined. This happened when I used the below code:
var d = new createDialog("Sample dialog. Exit?", function() {
console.log(d.No);
}, function() {
console.log(d.Yes);
});
You are calling noClicked() and yesClicked() immediately inside constructor. I think you would want to call them on click of No and Yes. You need to add these functions to event listeners of the buttons. Try below snippet.
function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
this.dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
this.No = this.dialog.getElementsByTagName("button")[0];
this.Yes = this.dialog.getElementsByTagName("button")[1];
var dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle.innerHTML = title;
document.getElementsByClassName("dialogCon")[0].style.display = "flex";
this.No.addEventListener('click',noClicked);
this.Yes.addEventListener('click',yesClicked);
}
var d = new createDialog("Sample dialog. Exit?", function() {
console.log(d.No);
}, function() {
console.log(d.Yes);
});
<div class="dialogCon">
<div class="dialog">
<h1></h1>
<button type="button">No</button>
<button type="button">Yes</button>
</div>
</div>