Invoke a function in an object based on a specified property dynamically

I have a component that receives parameters and needs to call dynamic functions provided in the params. The challenge is that these functions are dynamic, so they need to be defined before being passed.

Here is an example of the parameters that can be passed to the component:

export class ExampleConfig {
 baseScope: any;
 functions?: { eventName: string, eventType: string, eventFunction: Function}[]
}

This is how I populate the parameters and pass them to the component. By specifying the desired functions in the eventFunction property:

  ngOnInit(): void {
   this.componentConfig = {
       baseScope : this,
       functions: [
         { eventName: 'click-event', eventType: 'click', eventFunction: this.handleClick},
         { eventName: 'hover-event', eventType: 'hover', eventFunction: this.handleHover},
       ]
    };
  });
 }

handleClick(){
}

handleHover(){
}

Now that I have both the main scope and the function, I need to locate the method within the main scope.

this.exampleConfig.functions.forEach(func => {
// Here we have func.eventFunction which was previously defined and exists in the main scope
// We need to find func.eventFunction within the main scope and dynamically call it, for example calling handleClick
})

Currently, I am using the following syntax to pass the scope to the function:

func.eventFunction(this.exampleConfig.baseScope);

Within my function, I include a parameter to access the main scope:

handleClick(scope: any) {
// Instead of accessing properties directly as this.someProperties, I use scope.someProperties. I aim to call it directly without passing the scope parameter.
console.log("called");
}

The objective is to call it directly without requiring the scope parameter to be passed.

Answer №1

To implement binding, the Function.prototype.bind method can be utilized.

edit() {
  console.log("called");
  console.log(this.someproperties);
}


fnc.buttonFunction.bind(this)();

Alternatively, you can bind the scope at the function declaration:

{
  buttonName: 'data-del',
  buttonEvent: 'hover',
  buttonFunction: this.delete.bind(this),
},

Answer №2

To use the function, simply invoke it just like you would with any other function, as long as the `fnc` object has the property and is a callable function

this.someconfigs.functions.forEach(fnc => {
  // Call the function
  fnc.buttonFunction();
})

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

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Changing the content of a DOM element containing nested elements using JavaScript/jQuery

Need some help with a DOM element that looks like this: <span>text</span> <b>some more text</b> even more text here <div>maybe some text here</div> How can I replace text with candy to achieve this result: <span> ...

What are the reasons for the success function not being called and what steps can be taken to correct it

Whenever I attempt to submit the post, the data is successfully sent and received by the server, but the success function never gets called. In the network inspector tab of Chrome, the connection shows as stalled with a warning: "connection is not finished ...

Retrieve the two latest items in a dictionary array based on their order date

I've been browsing through similar discussions, but I just can't seem to grasp the concept. The JSON data for my current item appears to be more complicated than I anticipated. Here is a snippet of the lengthy JSON data: items = [ { ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...

searching for trees recursively in JavaScript

I am trying to develop a function that can search through an array containing nested arrays to find a specific node with information, similar to navigating a tree structure. const data = [ { id: '1-1', name: "Factory", children: [ ...

Is there a possible solution to overcome the type error when utilizing dynamic environment variables in conjunction with TypeORM and TypeScripts?

I'm currently working on a backend project using the TsED framework, which leverages TypeScript and ExpressJS. To work with TypeORM, I have also integrated the dot-env package in order to utilize custom environment variables sourced from a .env file ...

What steps can be taken to allow for the addition of multiple slick sliders using the same class on a single page?

When using the admin panel, the user has the ability to add multiple sliders to the page. How can all sliders with the same class be initialized? Is there a way to ensure that the control buttons for each slider are applied individually, instead of just f ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Utilizing a backbone collection in conjunction with a view to render a template

I am currently working on integrating with a 3rd-party API that returns an object containing an array. My goal is to transform this data into a backbone collection and then display it in a view. I have experimented with different approaches, with my late ...

Is there a way to store JSON data in a constant variable using Node Fetch without encountering the error TypeError [ERR_INVALID_URL]: Invalid URL?

In my current NodeJS project, I am working on extracting data from a JSON file and then sending it to a constant variable in my app2.mjs. The goal is to organize this data into an array of objects and eventually save it into a database. However, when tryin ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Error: The specified element "div" configuration is not found in the view

Trying to include a <div> element in a react-native project, but encountering an error message in the simulator: Invariant Violation: View config not found for name div Is there a way to render <div> in react-native without issues? Sample code ...

Sending every piece of information to the URL may not be the most efficient approach, in my opinion

Lately, I have incorporated NodeJS into my Angular project and here is how I am currently implementing it: Node : app.get('/register/:username/:password', function(req, res){ db.collection('users').insertOne({ username: req ...

Is it possible to replicate two arrays in Angular through echoing?

I've run into an issue where I am struggling to return two arrays from an ajax request between Angular and PHP. Each array works fine on its own, but when trying to return both together, I encounter problems. I attempted to place the two arrays within ...

Retrieving current element in AngularJS using jQuery

I have 4 templates, each with mouse actions that trigger functions: ng-mouseover="enableDragging()" ng-mouseleave="disableDragging()" Within these functions, I update scope variables and would like to add a class using jQuery without passing any paramete ...

What is the best method for sending data, including the CSRF token, from an AngularJS controller to a REST controller

I have been struggling to send data from a modal using an angular controller to a REST controller. The PUT, GET, POST methods only work when CSRF is disabled, but as soon as I enable CSRF, the PUT and POST methods stop working. The console log shows 405 (M ...

Are there any limitations imposed on keydown events in JavaScript when attempting to modify the browser's

I attempted to implement a JavaScript keydown event that would refresh the page, but unfortunately, it did not function as intended. Interestingly, the same code works flawlessly when triggered by a button click event. I'm in search of a solution to r ...

What could be causing the Javascript redirect code to malfunction in Internet Explorer 8?

My JavaScript code redirects users successfully in FireFox and Chrome browsers, but it does not seem to work in IE8. window.location ="/public/index/offer?act=search"; I would appreciate any assistance with this issue. Thank you. ...