1
class Controller {

    constructor(names){
        this.names = names;
    }

    sayhello(name){
        console.log("Hello " + name);
    }

    makeLink() {
        this.names.forEach(function(name){
            var link = document.createElement('li');
            link.innerHTML = name;
            var container = document.getElementById('container');
            container.appendChild(link);
            link.addEventListener('click', (event) => {
                sayhello(event.target.innerText);
            });
        });
    }
}

Here is an example of what I am trying to do in my actual code. I want to trigger the class method 'sayhello' when the 'li' is clicked, so that that it prints out the name corresponding to the 'li'. However, it doesn't seem to be working. I tried searching for a solution but still haven't had any luck finding it. Does anyone know how I might make this work?

Nipun Thennakoon
  • 3,586
  • 1
  • 18
  • 26
christine
  • 51
  • 3

1 Answers1

2

sayhello does not exist in makeLinks' scope, but in its context ( aka this), so you have to take care to not loose context through that forEach function, then you can easily access it:

makeLink() {
    this.names.forEach((name) => { // <----
        var link = document.createElement('li');
        link.innerHTML = name;
        var container = document.getElementById('container');
        container.appendChild(link);
        link.addEventListener('click', (event) => {
            this.sayhello(event.target.innerText); // <----
        });
    });
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151