0

I am building a project that passes in a JSON object to config and display my popup modal, and in the config object, I also pass in the the function name that once the button in the modal is clicked, that function should be called. However, I couldn't seem to get it to work and here is my code:

This is the configuration of my modal:

configuration = {
    icon: 'question',
    title: 'Import Employees From Google Workspace',
    content: 'Are you sure to import ' + numOfPeople + ' users from Google Workspace to Ceebig One HRM?',
    cancelable: true,
    action: {
      buttonText: 'Import',
      buttonAction: platform.value === 'google' ? 'importGoogleUsers' : 'importMicrosoftUsers'
    },
    parameters: {
      users: selectedPeople.value
    }
  }

In this case, the function name I could like to call is importGoogleUsers In my popup modal, when the button is clicked, the callFunction method is executed, and here is the implementation of the callFunction method:

<script setup>
import { execFunction } from "./HRM/controllers/HRMFunctions.js";

const props = defineProps(['configuration', 'open'])

function callFunction(funcName) {
  execFunction(funcName, props.configuration.parameters)
}

</script>

The funcName parameter, in this case is importGoogleUsers is being passed in as a parameter. Here is the file that has the implementation of execFunction and importGoogleUsers:

function execFunction(functionName, parameters) {
  this[functionName](parameters)
}

function importGoogleUsers(parameters) {
  console.log('function called')
  const { users } = parameters
}

export {
  execFunction,
  importGoogleUsers
}

When the button is pressed in the modal, I am expecting to see console log statement function called, however I am getting error saying: enter image description here

I am not sure why this is happening, please help.

Edit 1: I also tried window[functionName](parameters), same error

Jacky.S
  • 364
  • 5
  • 17
  • 1
    `this[functionName]` should be `window[functionName]`. – Barmar Mar 27 '23 at 19:47
  • I tried `window[functionName]`, same error @Barmar – Jacky.S Mar 27 '23 at 19:53
  • I think modules don't put global variables/functions into the `window` object. These shouldn't be global functions, put them all into an object. – Barmar Mar 27 '23 at 19:54
  • @Barmar could you please more specific, what does that look like, please – Jacky.S Mar 27 '23 at 19:55
  • I'm not sure how it integrates with Vue, but something like `const callableFunctions = {importGoogleUsers, ...}`. Then do `export {execFunction, callableFunctions}`, and then later you use `callableFunctions[name]` – Barmar Mar 27 '23 at 20:20
  • It is much easier for you if you handle the logic by a switch case: `if(functionName == 'A') A()` – Duannx Mar 28 '23 at 02:15

0 Answers0