Developing a function utilizing text data

Deciding to dive into Vue and Javascript, I attempted to streamline some code but ended up doing the opposite.

So here's the issue: I have a data object in vue:

            eventOptions: {
                eventType: {
                    data: [],
                    method: 'getEventTypeList',
                    service: 'ReportEventService',
                },
                eventSeverity: {
                    data: [],
                    service: 'ReportEventService',
                    method: 'getSeverityList',
                },
                eventImpact: {
                    data: [],
                    service: 'ReportEventService',
                    method: 'getBusinessImpactList',
                },
                eventStatus: {
                    data: [],
                    service: 'ReportEventService',
                    method: 'getEventStatusList',
                },
            },

My goal is to loop through this object and create a function like:

ReportEventService.getEventStatusList()
which refers to an imported javascript file.

        async setEventOptions() {
            const promises = Object.keys(this.eventOptions).map((key) => {
                const { method, service } = this.eventOptions[key];
                return new Promise(async (resolve, reject) => {
                    try {
                        const response = await service[method]();
                        resolve(response);
                    } catch (e) {
                        reject(e);
                    }
                });
            });

            Promise.all(promises)
                .then((responseArray) => {
                    Object.keys(this.eventOptions).forEach((key, index) => {
                        this.eventOptions[key]['data'] =
                            responseArray[index].data;
                    });
                })
                .catch((e) => console.log(e));
        },

However, I encountered a problem.

This line causes an error:

const callback = service[method]();

Is there a way to combine two strings to create a functional execution? Although I do realize that this approach may be redundant, and it would be easier to simply list them out individually.

I experimented with:

const func = new Function(`${service}.${method}()`)

The resulting error is: TypeError: service[method] is not a function

Answer №1

Object literals are versatile and can store objects, classes, functions, and more.

Currently, you are only storing a string, 'ReportEventService', which leads to calling the method like 'ReportEventService'[method]() - this doesn't make much sense.

However, if you store the actual object that represents ReportEventService, then you would call it like ReportEventService[method]()

In other words: service: ReportEventService, as opposed to service: 'ReportEventService',

Answer №2

Why rely on strings if you can incorporate them into eventOperations? Utilize callbacks instead:

eventType: {
    data: [],
    method: 'getEventTypeList',
    service: 'ReportEventService',
},

Transform it to:

eventType: {
    data: [],
    callback: () => ReportEventService.getEventTypeList(),
},

Then, you simply make the call:

const response = await callback();

By doing so, you have access to more tools for code verification. Renaming refactoring will function effortlessly without dealing with arbitrary strings. You can also confirm if the method is valid and verify that it is called with the correct number of parameters.

Additionally, this approach offers flexibility - should you modify

ReportEventService.getEventTypeList()
in the future to necessitate parameters, adjusting the callback to
() => ReportEventService.getEventTypeList("foo", 42)
can be done seamlessly without altering the consuming code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a base64 image in a new tab with JavaScript on iOS devices

Currently, I am receiving base64 data for an image and would like to open it in a new tab. To achieve this, my code looks something like this: var window = new window(); window.open("<iframe src="+base64Url+"); Interestingly, this method works perfec ...

An Illustration of Basic Nested Controller within Directive Parameters

Check out this code snippet app.directive('hello', function() { return { restrict: "E", templateUrl: "/Angular/Modules/Selector.html", controller: function () { this.message = [enter the attribute message he ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

Creating a curved exponential data set with specific endpoints and a set number of data points

Struggling to create a function that involves math skills, I could really use some assistance. The task is to design a function that takes data points x and generates an array of size x with exponentially increasing values from 0 to 100. It would be ideal ...

Issue with Confirming Password in Laravel Validation

I am currently incorporating Vue.js into my Laravel project and I am facing an issue with validating a confirmation password. Despite entering matching passwords, I continue to receive an error stating that they do not match. <div class="control-grou ...

Exploring the World with the vue-i18n Plugin

Recently, I have integrated translation into my app and now I am looking to implement a button event that allows users to change the language on the home page. For this task, I referred to two tutorials: Localization with Vue and Localization with Vue Tut ...

I am attempting to transmit an Error Object through an Axios POST request, but the server is receiving an empty Object

Hey everyone, I'm currently working on creating a Logging Microservice specifically for capturing frontend errors. The goal is to log all errors in a specific format like the example below: catch(err){ sendToLogs({message: 'Could not read input ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

Tips for designing a Quasar page that dynamically loads content as the user scrolls

I am attempting to develop a component that will render multiple elements as the page is scrolled. I am utilizing the Quasar framework for Vue.js. Below is the code required to render a single block containing information from a JSON file: Quasar comes wi ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

Error encountered: Multer does not recognize the field when attempting to upload multiple files in a node.js environment

I would like to upload two files in one request using Node.js and I am utilizing multer for this task. Here is my request in Postman: https://i.sstatic.net/8ZEno.png Additionally, I am using multer in routing: router.post( "/Create", Uploa ...

The browser freezes after a short delay following an Ajax request

I recently created an admin panel with notification alerts using Ajax. Initially, everything was working smoothly, but after a few minutes, the browser started freezing. I'm new to Ajax development, so I'm unsure what could be causing this issue. ...

Beginner's guide to integrating the @jsplumb/browser-ui into your Vuejs/Nuxtjs project

I am working on the integration of @jsplumb/browser-ui community edition into my application. After receiving a recommendation from the team at jsplumb, I decided to utilize @jsplumb/browser-ui. However, I am facing difficulty in understanding how to begin ...

What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheet ...

Determine the width of the window and adjust the positioning of jQuery UI tooltips accordingly

Struggling to adjust the jQuery UI tooltip position based on screen width, but can't seem to figure it out. Can someone assist me in detecting the browser's width and changing the tooltip position accordingly? [fiddle] $(function () { $(doc ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...

Select the even-numbered occurrences of a specific class in CSS using the nth-child()

I am encountering an issue with my table layout. The structure is similar to the following: <tbody> <tr class="row">...</tr> <tr class="row--expanded">...</tr> <tr class="row">...</ ...

The Vue design is not being reflected as expected

Encountering a peculiar issue where the style in my Vue component is not being compiled and applied alongside the template and script. Here's the code snippet: To achieve an animated slide fade effect on hidden text upon clicking a button, I've ...