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

How to execute a function passed as a string argument?

An application has some buttons on a screen that should execute different functions when clicked. It goes like a little like this:

<template>
<ul>
<li v-for="MenuItem in MenuItems">
  <button type="button" @click.prevent="handleClick({Function: MenuItem.Function.Name, Params: MenuItem.Function.Params })">
              {{ MenuItem.Label }}
  </button>
</li>
</ul>
</template>

<script setup>
const MenuItems = [
{
              Label: `Edit`,
              Function: {
                Name: `editItem`,
                Params: {
                  ItemID: 1
                }
 },
{
              Label: `Delete`,
              Function: {
                Name: `deleteItem`,
                Params: {
                  ItemID: 1
                }
 }
]

function handleClick({Function, Params}) {
   Function.apply(Params) // throws not a function error
   eval(Function+"()")    // throws not a fuction error
}

function editItem(){
console.log(`edit item`);
}

function deleteItem(){
console.log(`about to delete item`);
}
</script>

All I want to do is run whatever has been passed to the Function argument in handleClick() and also include the Params argument as an argument to the Function that needs to be executed e.g. editItem(1) or deleteItem(1);

Trying apply() and eval() don’t seem to work and throws an error that Uncaught TypeError: Function.apply is not a function. I am using VueJS as the framework, but this is really a Javascript question.

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 :

If you don’t reference functions in <script setup> they are removed in the production build. Make them as a part of a referenced object:

Playground

const Functions = {
  editItem,
  deleteItem
};

function handleClick({Function, Params}) {
  Functions[Function](Params);
}

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