Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: node.onclick call a function not working

I use a loop through the node elements to get the ID from the clicked element. Until then all good and it works. Now I want to call an another function in my class & get this error:

this._PreLoad is not defined at HTMLElement.s.onclick

this._joinnews.forEach((node) => {
    node.onclick = function(){
        const requestData = `newsid=${node.id}`;
        // some code // 
        this._PreLoad(true); // ERROR
        // _PreLoad(true); not working
        // this._PreLoad(true).bind(this); not working (I am not yet familiar with the bind function)
    }
});

Are the functions inside a node loop unknown ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The correct place to bind this is here:

node.onclick = function() {
    const requestData = `newsid=${node.id}`;
    // some code // 
    this._PreLoad(true);
}.bind(this); // bind here!

Alternatively, use an arrow function which preserves this as whatever it was at the time of the function declaration:

node.onclick = () => {
    const requestData = `newsid=${node.id}`;
    // some code // 
    this._PreLoad(true);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading