How can multiple instances of a JavaScript function be executed with varying arguments?

Currently, I am using the ExtJS framework and running one method multiple times with different parameters.

I am seeking a more consistent, easy, and maintainable approach to handle this. Would vanilla Javascript solutions be the way to go?

I attempted to collect each param into an array and use methods like Array.map() and forEach(), but I have not been successful.

Thank you in advance.

//ExtJS class:
Ext.define('MyApp.FooClass', {
    extend: 'Ext.panel.Panel',

    items: [
        MyApp.createFooCard('Func1Param1', 'Func1Param2', 'Func1Param3'),
        MyApp.createFooCard('Func2Param1', 'Func2Param2', 'Func2Param3'),
        MyApp.createFooCard('Func3Param1', 'Func3Param2', 'Func3Param3'),
    ]
});

It is evident that the same method is used with different arguments for each instance.

//And here is the related factory-function:
createFooCard: (bindValue, userCls, glyph, label) => {
        return {
            itemId: bindValue,
            userCls: userCls,
            glyph: MyApp.getGlyph(glyph),
            items: {
                xtype: 'infocardfld',
                fieldLabel: label,
                bind: '{' + bindValue + ' || "0"}'
            }
        }
    }

Answer №1

The process involves utilizing Array.prototype.map to gather nested arrays and passing them along using Spread syntax for execution in a factory function. Here is the recommended approach:

Ext.define('MyApp.FooClass', {
    extend: 'Ext.panel.Panel',

    items: [
              ['Func1Param1', 'Func1Param2', 'Func1Param3'],
              ['Func2Param1', 'Func2Param2', 'Func2Param3'],
              ['Func3Param1', 'Func3Param2', 'Func3Param3']
           ].map(args => MyApp.createFooCard(...args));
    });

Answer №2

If you have an array called Items in the global scope, you can conveniently add elements to it within the function createFooCard. Here is an example:

// Array to store elements

var items = []

// Function to create a card

function createFooCard(bindValue, userCls, glyph, label) {
    var temp = {
        itemId: bindValue,
        userCls: userCls,
        glyph: MyApp.getGlyph(glyph),
        items: {
            xtype: 'infocardfld',
            fieldLabel: label,
            bind: '{' + bindValue + ' || "0"}'
        }
    };

    items.push(temp);
}

You can also pass the array as a parameter for a more generic approach.

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

What is the best way to retrieve a property with a period in the method name in JavaScript?

One dilemma I'm facing is trying to access the tree.removenode method through chartContext in Angular. It's been a challenge for me to understand how to achieve this. https://i.stack.imgur.com/yG7uB.png ...

Differentiating the texture of a pointCloud in three.js shaderMaterial: A step-by-step guide

Utilizing THREE.PointCloud for optimum performance, I aim to animate 100,000 objects. However, I am facing an issue with setting different textures for particles. How can I incorporate uniforms with various textures in this code? Is it possible to pass s ...

Error encountered: Syntax error found while attempting to build in ReactJS with an unexpected token "<"

While accessing localhost:3000/, the login page appears for the frontend without any issues. However, when trying to visit localhost:3000/admin/login, a blank page is displayed. This discrepancy seems to occur when using NPM run build, as opposed to NPM st ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

After an orientation change event, the window.innerWidth property is behaving unexpectedly in Chrome iOS version 87.0.4280.77

After an orientation change event on Chrome iOS 87.0.4280.77, the window.innerWidth appears to be incorrect. Initially, the innerWidth is 414px when viewed on an iPhone. However, after changing the phone's orientation from landscape to portrait, the i ...

What is the best method to detect a change in scroll position on a webpage using JavaScript?

Is there a way to trigger an event when the page's scroll position changes? I'm interested in creating a dynamic table of contents similar to (where the active item changes as you scroll). Can this be achieved without directly accessing the cu ...

The button's onclick function is not triggering with just one click

I am having trouble with a JavaScript function not being called on the first click. I have to click the button multiple times for it to execute. Here are the methods I have attempted so far: <a href="javascript:delete_todo(4);void(0)"><img border ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

Invoke a JavaScript function within a PHP file

My JavaScript file, named "my_js_stuff.js", has the following code: function my_js_function() { jQuery.ajax({ url: my_ajax_script.ajaxurl, data: ({action : 'get_my_comments'}), success: function() { //Do stuff here } }); This file is ...

The current URL in the browser does not change

My HTML form has a JavaScript function that involves handling the window.location.href. I successfully remove two unwanted query string parameters from the source using this function, as shown in the first and second alert screenshots. However, I encounte ...

Difficulty encountered when trying to use Bootstrap tooltip with Bootstrap icon

Attempting to implement bootstrap tooltips on bootstrap icons with the following code: <body> <script> const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Tips for including a background image using the :after pseudo-element in Angular 2

I'm facing a challenge with passing a URL image from my HTML to my CSS in Angular, and I can't seem to figure it out: Here is a snippet of my CSS: card-profile_visual { height: $visual-height; overflow: hidden; position: relat ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

Ways to retrieve directory information in Next.js hosted on Netlify

Having trouble retrieving a list of directories in Next.js on Netlify. The code works fine on localhost, but once deployed to Netlify, an error is triggered: { "errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": ...

How to Identify and Print a Specific Property in a JSON Object using Node.js?

Hey there, I'm having trouble extracting the trackName from the JSON object provided here. I've tried accessing it using this code: console.log(res.text.results[0].trackName); but unfortunately, I keep getting this error message: TypeError: Cann ...

Can Angular 5 integrate with Pusher?

Below is the javascript code used to integrate Pusher into native HTML: <head> <title>Pusher Test</title> <script src="https://js.pusher.com/4.1/pusher.min.js"></script> <script> // Enable pusher logging - don't i ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Is it possible to reload the webpage just one time after the form is submitted?

Can anyone suggest how I can refresh the webpage using PHP after submitting a form? I've been searching for a solution but haven't found one yet. Your assistance would be greatly appreciated. ...