Javascript function that adjusts dynamically

I have arrays within an array that are created and passed as arguments in a method of an object like this:

myObject.method([
    {
        id: "mystring",
        myfun: function(g) {
                   return 'Value: ' + g.value + g.rows[0]['value'];
                   },
        a: "mysecondstring"
    },
        id: "mystring_a",
        myfun: function(g) {
                   return 'Value: ' + g.value + g.rows[0]['value'];
                   },
        a: "mysecondstring_a" 
    }]);

This setup works well throughout my code. However, I now need to change the myfun: function(g)... at runtime, which means I have to declare my associative array before calling myObject.method(). Here is what I attempted:

myfun: new Function("g", "return 'Value: ' + g.value + " + my_dynamic_variable)

That didn't work, so I tried:

var fn = new Function("g", "return 'Value: ' + g.value + " + my_dynamic_variable)

along with

myfun: fn(g)

and also

myfun: function(g) { return fn }

and

var fn = function(g) { return eval('Value: ' + g.value + my_dynamic_variable) }

with

myfun: fn

Every attempt I made resulted in null for g once the myfun code was executed. It seems like variable g needs to be bound within the scope of myObject, and can't be defined outside of that scope, but I'm not entirely sure.

Does anyone know a way to accomplish this? Am I on the right track or missing something here? Thank you!

Answer №1

To keep that function for later use, simply assign it to a variable:

let myFunction = function(element){return 'Result: '+ element.textContent + element.children[0].textContent}

Next, you can pass the reference of the function like so:

callbackFunction: myFunction

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 function of '@' symbol in coding?... obtain {ModuleName} from '@ModuleName'

What is the significance of the '@' symbol in imports? I've noticed that various modules like '@react-navigation', '@babel', and others use the '@' symbol. Does this symbol serve a specific purpose, or is it s ...

A guide on interpreting the details of the stripe webhook response

I have successfully set up a ColdFusion file to intercept the response from the STRIPE webhook. <cfsavecontent variable="headerdump"> <cfdump var="#toString(getHttpRequestData().content, 'utf-8')#" expand="yes" format="text"> < ...

When was Chrome first updated to include timezone offset support for Intl.DateTimeFormat()?

My experience with Chromium 121 has been positive using the Intl.DateTimeFormat as shown below: new Intl.DateTimeFormat('en', { dateStyle: 'long', timeStyle: 'long', timeZone: '+0500', }).format ...

What is the best method to combine two arrays in this particular manner?

As a beginner in Python, I am trying to figure out how to concatenate arrays a and b in a specific manner. I have experimented with stack, vstack, hstack, concatenate, and other methods, but I have been unable to achieve my desired outcome. a= [[ 0], ...

Graph columns failing to display on Chart.js bar chart

I'm currently facing a challenge while trying to create a bar chart using HTML and JavaScript. Unfortunately, the bars are not showing up for some reason. I have included the code snippet below along with an imagehttps://i.stack.imgur.com/4H7ol.png. ...

Error message in Angular 9: "The 'pipe' property is not recognized on the 'void' type"

I recently created a function for streaming audio in Angular: private streamObservable(url) { new Observable(observer => { // Play audio this.audioObj.src = url; this.audioObj.load(); this.audioObj.play(); const handl ...

Tips for repositioning an element to the top of an array

Currently, I have extracted rows from a table. The row we are targeting has an id that matches $_GET['id']. My objective is to relocate this specific row to the top of the list. $sq = "select * from video order by ind asc"; $st = $db-&g ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...

Is there a way to verify whether a user is currently logged in? (Using everyauth in node.js)

Previously, I relied on client-side auth for my application. Recently, I integrated server-side everyauth and it's functioning well. However, I'm unsure how to perform a function similar to FB.getLoginStatus (which I used in the client-side) when ...

Efficient State Management with React-Redux for Streamlined HTTP Requests

In the process of developing a React-Redux application, I have encountered a situation where I need to display a cancel button while a specific HTTP request is ongoing. Upon successful execution of the request, the UI should display the results. If the use ...

What is the best way to place text inside a TH element without any text within the TH's child nodes?

When parsing a website and obtaining the instance of a TH element, I use innerText to extract the text I need. However, sometimes there is additional unnecessary text that I want to exclude. Is there a way to only retrieve the top-level text? var th_elem ...

Static compression in Express.js is failing to gzip the CSS and JavaScript files

I have created a basic server using Expressjs with the following code: 'use strict'; var express = require('express'); var app = express(); var compression = require('compression'); app.use(compression()); app.listen(process ...

An issue has been encountered while utilizing the *whatNWISdata* function from the *dataRetrieval* package provided by USGS: It is necessary for all parts of

I recently encountered an issue while attempting to retrieve all available data for specific USGS sites using the whatNWISdata function. Upon executing the function with the code snippet below: siteNo <- "09508300" dailyDataAvailable <- whatNWISda ...

Error: The value "'827'" cannot be assigned to "Course_Content.course_outline_id" as it must be a valid instance of "Course_Outline"

While working on my django view, I encountered an error stating: ValueError: Cannot assign '827': 'Course_Content.course_outline_id' must be a 'Course_Outline' instance. I attempted to convert it to an int but it still didn&ap ...

What are the reasons and situations where it is beneficial to utilize the input type

Could someone provide an explanation on this subject, detailing its purpose and how it should be understood? <input type="hidden" name="msg" value="GATEFORUM|OE180187|NA|0.00|NA|NA|NA|INR|NA|R|gateforum|NA|NA|F|AMIT SINGH|9993523486|gis16|NA|NA|NA|NA ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

"Error: React dotenv is unable to access the .env configuration file

My React and Node project has a .env file in the root directory, along with other important files like .eslint and .gitignore. The .env file contains 6 lines of code such as APIKEY=aeofiunoief, without any special symbols. Within the src/ directory, there ...

What are some methods to secure my API keys within my React application?

What steps can I take to secure my api keys in my react application? Should I incorporate something with express? My goal is to avoid creating any server-side components to handle the API calls. Currently, my backend is managed by firebase but I also uti ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

Setting properties on functions and defining their prototype

My task involves working on the following block of code: function Vector(x, y) { this.x = x || 0; this.y = y || 0; } Vector.add = function(a, b) { return new Vector(a.x + b.x, a.y + b.y); }; Vector.sub = function(a, b) { return new Vecto ...