How to execute a function whose name is in the database?

Asked

Viewed 81 times

1

I would like to know how to execute a Javascript function by taking its name in the database. Example:

data["nome_coluna"] // essa será a informação que estará no banco. (exemplo: somar();)

// Aí o objetivo é executar essa função dentro de um if.

if(data["nome_coluna"] != ""){
    data["nome_coluna"];
}

Is there a way to do that? Is that way wrong? If so, how to do?

NOTE: The purpose of this is to make that when I buy a card and it has a function that must happen immediately, then call the function that is saved in the database. As there are many cards, it is not feasible to keep doing an if for each letter, since they are different functions.

  • Only the function name. I need to call it inside if, only it will call the letter function in specific.

  • Currently with parentheses. but this is quiet to change, if it works without.

  • 1

    Anyway you will have to have on the page the code of all functions.

  • The code yes, but it is easier for me to call the function directly from the bank and do only one if, than to keep checking which card is and calling the function.

  • 2

    Try this, but only if the function name comes without the parentheses: if(window[data["nome_coluna"]]){
 window[data["nome_coluna"]]();
}

  • Man, it worked!!! Thank you very much, what this window does?

  • It takes the global variables.

Show 2 more comments

2 answers

1


You can check if the function exists before trying to run it. But for this the function must have global scope to call it with the object window:

if(window[data["nome_coluna"]]){
    window[data["nome_coluna"]]();
}

In this case the function name should come without the () in the variable data["nome_coluna"]. The object window has as properties the functions created in the page with global scope (can have a notion of scope in this documentation).

0

In order to do this you can create a class and use as follows;

If she’s in your filing cabinet or properly imported, you can call it minhaClasse.['nome_coluna']() or this.['nome_coluna'](), will depend on the context.

Using your example and considering it’s coming from the bank without the ():

data["nome_coluna"] 

if(data["nome_coluna"] != ""){
    minhaClasse.[data["nome_coluna"]](); // Ou como eu disse
    // minhaClasse.[this.data["nome_coluna"]](); // Não sei o seu contexto
}

I believe it runs like this.

It has the way that Sam spoke up too, to use without class, window[data["nome_coluna"]], if you come with the (), and window[data["nome_coluna"]](), if you come without the ()

  • In my context here, it didn’t work that way! But thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.