0

So I know this question has been asked a few time but I can't find a solution which is working for me and I don't understand how does this properly work.

Here is the function involved :

import form from "./form"; //return some html
function changePage(e){
    console.log(e.target.dataset.component) // equal "form"
    //loadComponent(form) => is working 
    loadComponent(eval(e.target.dataset.component)) // => form is not defined    
}

function loadComponent(name)
{
    const wtv = name()
    document.getElementById('app').append(wtv)
}

So how can I dynamicaly call e.target.dataset.component ?

Baldráni
  • 5,332
  • 7
  • 51
  • 79
  • See https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – Christoph Lütjen Jan 23 '19 at 16:12
  • You're doing your `eval( ... )` in the wrong place. It would have to be inside `loadComponent()`, and you'd have to modify the function to support both functions _and_ strings. – Tyler Roper Jan 23 '19 at 16:12
  • See https://stackoverflow.com/a/25859853/128165 on how to use eval in the correct context, but the [answer](https://stackoverflow.com/a/54331392/128165) here is the one to use. – Gabriele Petrioli Jan 23 '19 at 16:15
  • Its worth saying using eval is the worst alternative ever. eval's are insecure, very slow and extremely expensive. – Merak Marey Jan 23 '19 at 16:17

1 Answers1

3

Most certainly you need a mapping from labels to functions:

import form from "./form"; //return some html

const datasetToComponent = {
  'form': form
};

function changePage(e){
  if (datasetToComponent[e.target.dataset.component]) {
    loadComponent(datasetToComponent[e.target.dataset.component]);
  }  
}

function loadComponent(name) {
  const wtv = name()
  document.getElementById('app').append(wtv)
}
David
  • 3,552
  • 1
  • 13
  • 24