Hi, I have fName, lName, and position set to empty string and I want their value to be changed after clicking the button and to save that value to the this.templates ${this.fName} etc.
the showMessage method should receive the click and update the values and inject a template. Everything is fine apart of updating the values. When it gets to the "mP.innerHTML = _this.template;" line the values are empty just as set at the start.
Weird thing is that the console.log(_this.fName) that runs before "mP.innerHTML = _this.template;" gives out a correct value on click.
What could be the problem? How do I solve this?
class Message {
constructor() {
this.fName = '';
this.lName = '';
this.position = '';
this.bride = {
fName: 'Anna',
lName: 'Doe',
position: 'bride'
};
this.groom = {
fName: 'John',
lName: 'Doe',
position: 'groom'
};
this.template = /*html*/`
<div class="message message-show">
<div class="message-close">x</div>
<h1>
My name is ${this.fName} ${this.lName}, ${this.position}
</h1>
</div>`;
this.elements = function() {
let messageButtons = document.querySelectorAll('.wed-couple-newlyweds-message');
let messagePopup = document.querySelector('.message-popup');
let messageClose = document.querySelector('.message-close');
let messageDiv = document.querySelector('.message');
return {
messageButtons: messageButtons,
messagePopup: messagePopup,
messageClose: messageClose,
messageDiv: messageDiv
};
};
//Initiate Methods
//End of Methods.
}
//declare methods
// 1. show message on click.
showMessage() {
var _this = this;
let els = new this.elements();
let mB = els.messageButtons;
let mP = els.messagePopup;
let mD = els.messageDiv;
mB.forEach(function(message) {
message.onclick = function() {
if (message.classList.contains(`wed-couple-newlyweds-message-bride`)) {
console.log('bride')
_this.fName = _this.bride.fName
_this.lName = _this.bride.lName
_this.position = _this.bride.position
console.log(_this.fName)
mP.innerHTML = _this.template;
} else {
console.log('groom')
_this.fName = _this.groom.fName
_this.lName = _this.groom.lName
_this.position = _this.groom.position
console.log(_this.fName)
mP.innerHTML = _this.template;
}
let mC = els.messageClose;
_this.closeMessage();
}
});
};
A template literal like
var foo = `Hello, ${name}`;
is equivalent to:
var foo = "Hello, " + name;
It takes the values of variables at the time it is interpreted and produces a regular string.
It does not create any kind of string-like object which dynamically updates its value by watching the values of the variables that were interpolated.
If you want to get a new string, using the new values of the variables, then you need to rerun the code.
Make it into a function.