Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls.

I'm aware that using `eval` is deemed unsafe and not the most ideal method. However, at present, I'm struggling to come up with an alternative solution that aligns with my requirements.

Is there a more secure or effective way to achieve the same functionality?

vm.saveRecord = function() {
    var service = '';

    if(vm.valueTrue) {
        service = vm.otherValue ? 'function1' : 'function2';
    } else {
        service = vm.otherValue ? 'function3' : 'function4';
    }

    eval(service).callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

Answer №1

Utilizing a function handle is key when it comes to executing functions efficiently. The function handle serves as a reference to the specific function that needs to be executed:

//pre-existing functions
function first() {   console.log("first")   };
function second() {   console.log("second")   };
function third() { console.log("third") };

//function responsible for executing other functions
function execute(num) {
  //declaring a variable to store the chosen function
  let toRun;
  
  //determining which function to execute based on input number
  if (num == 1) {
    toRun = first;
  } else if (num == 2) {
    toRun = second;
  } else if (num == 3) {
    toRun = third;
  }
  
  //calling the assigned function by using ()
  toRun();
}

//executing different functions
execute(3);
execute(2);
execute(1);

Answer №2

To streamline your code, you have two options:

vm.saveRecord = function() {
    var service = vm.valueTrue
            ? vm.otherValue
                ? doTaskA
                : doTaskB
            : vm.otherValue
                ? doTaskC
                : doTaskD;

    service.callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

Alternatively, you can group the functions in an object with keys as accessors.

vm.saveRecord = function() {
    var services = { doTaskA, doTaskB, doTaskC, doTaskD },
        service = vm.valueTrue
            ? vm.otherValue
                ? 'doTaskA'
                : 'doTaskB'
            : vm.otherValue
                ? 'doTaskC'
                : 'doTaskD';

    services[service].callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

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

AngularJS: Substates not rendering properly

I'm encountering issues while trying to incorporate nested states in my project. Although the View template and JavaScript calls are being made and loaded, the screen is not changing - in other words, the nested screen is not displaying. http://{dom ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following: var stateDat = { ME: ['Maine',1328361], etc. }; Into this structure dynamically within a function? var stateDatHistory = { 1:[ ME: ['Maine',1328361], etc. ], 2:[ ME: ['Maine& ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

"Need help solving the issue of generating a random number for a Firebase DB column after adding a new user

Whenever I add a new user using JavaScript, it generates a random number below the Admins column like this. However, I want to adjust this so that it appears as shown in these tables, displaying the username value. If anyone can help me modify the code acc ...

Vue Array Proxy Class Fails to Trigger Reactivity

My custom Array extension has a feature where it intercepts changes made to its properties using Proxy, which is returned from the constructor. However, when used in a Vue component, it encounters issues. For example, when a filter is added, the display do ...

Customize the styling of an individual 'LI' item within an array by utilizing Jquery

Just starting out with Javascript and jQuery. Created a basic image slider that's running into a jQuery problem. Here's the HTML for the image list: <div id = "slider-auto"> <ul class= "slides"> <li class = "slide"&g ...

Error: Unable to locate module during module creation

I encountered an error while trying to import a module in my test application. ../fetchModule/index.js Module not found: Can't resolve './Myfetch' in '/Users/******/nodework/fetchModule' Here is the folder structure: And her ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

I'm currently attempting to upload a file to a Django server utilizing AngularJS 1.6.5. Unfortunately, I'm encountering issues with uploading the file using the $http.patch method

I am currently working on uploading a file from an AngularJS 1.6.5 application to a Django server. However, I am facing some challenges with the 'Content-Type' header that needs to be passed along with the $http.patch method. Here is how my Angul ...

What is the best way to include a dialog div within a form tag?

I am facing an issue with a JQuery dialog on my webpage. The data entered into the dialog seems to get lost because the dialog is placed outside the form tag. Here is how it appears: https://i.stack.imgur.com/fnb07.png So far, I have attempted this soluti ...

Utilizing jQuery to extract the `h1` element from a dynamically loaded external page within the

I am facing a challenge in selecting an h1 element from a remote page that I have loaded into $(data). Despite several attempts, I am struggling to write the correct code. When I use this code: console.log($(data)); The output is as follows: [text, meta ...

Using the same ng-model to show distinct values in two separate input fields

I have a form with a dropdown list that loads data using the ng-model="placeid". When a user selects an option from the dropdown, I want to display the selected place's latitude (place.lat) in an input box. Here is the dropdown list code: <select ...

Utilize form controller to reference form controls that are dynamically named

Imagine a scenario like this (note that this example is artificially created): <form name="myForm"> <input name="{{'myInput'}}" ngModel="data.myInputModel"> </form> In my understanding, referencing it should be like: $scope ...

The nested directive link function failed to execute and the controller was not recognized

Apologies in advance for adding to the sea of 'mah directive link function isn't called!' posts on Stack Overflow, but none of the solutions seem to work for me. I have a directive named sgMapHeader nested inside another directive called sg ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

"Enhance Your Website with jQuery Mobile's Multi-Page Setup and Panel

I am currently facing the challenge of managing multiple pages within a single document and I would like to utilize jQM 1.3's Panel widget to control navigation between these pages. However, the issue arises from the requirement that Panels must be co ...