injecting a parameter into a JavaScript function

Is it possible to pass a variable called "templateBody" into a function in this code snippet?

function GetMenu(){
 var templates = [{name:"maher",body:"<p>Maher test</p>"},{name:"Jeremy",body:"<p>Jeremy test</p>"}]
 var payload = []
 for (var i = 0; i<templates.length; i++){
   var templateBody = templates[i].body
     payload.push({
       text : templates[i].name,
       onclick: function(templateBody){tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);}
 })
}
return payload
}

Answer №1

Passing a variable is only possible when calling a function, which you are not doing in this case. However, since all JavaScript functions act as closures, any variables defined in a higher scope will still be accessible without any special actions needed.

The problem with the provided code arises from the shadowing of the variable templateBody by its own parameter. To resolve this issue, simply remove the conflicting parameter:

function(templateBody) -> function()

Another concern is that a function is being created inside a loop, which can cause complications with closures. There are solutions available, such as those discussed in this link: JavaScript closure inside loops – simple practical example

Answer №2

Here is what you have:

function(templateBody){
  tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);
}

Based on the property name, it seems like this code will be executed when the user clicks on something ('onclick' event). This will pass an event that will be injected as templateBody into the function, instead of using the previously defined templateBody.

Additionally, the usage of templateBody as a closure in a loop means it may not stay consistent for the specified functions. It's recommended to implement a proper closure pattern like so:

(function(templateBody){
  return function() {
    tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);
  }
})(templateBody);

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

RequireJS has an unbreakable reliance on the library

For my Angular + Require project, I encountered an issue while trying to package the application with r.js using: node r.js -o app.build.config.js Despite everything working fine, the library files were not found on the specified path. Instead, the depen ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

What are some ways to slow down the speed of my animation?

Currently, I am creating a HTML5 game where I have implemented javascript to make my character move in response to the user pressing the arrow keys. The movement animation consists of 6 sprites. However, I have encountered an issue where when I hold down ...

Expanding the capabilities of indexable types in Typescript

I recently created an interface for form validation. Here is the initial structure: export interface SearchBarValidatorObj { [k: string]: KeyObjectValidator; } However, I am wondering if there is a way to add a "static" type to it in order to achieve ce ...

Receive emails: using the require() function with ES Module

After following the react-email documentation, I encountered an error when trying to run the yarn email command: $ email dev --port 3001 ***\node_modules\ora\index.js:65 if (process.platform === 'win32') { ...

What is the best way to retrieve and save the titles of checked boxes in the Autocomplete using state with hooks?

I've implemented the React Material-UI Autocomplete feature with checkboxes in my project. Here is what I have so far in my code (check out demo.js for details): https://codesandbox.io/s/material-demo-rxbhz?fontsize=14&hidenavigation=1&theme=d ...

Make sure to include the "active" class in the pager once the slider begins

After coming across this fiddle, I noticed that it closely resembles the task I am working on. However, there is one issue - currently, only the first item has an active class when the slider autostarts. The next or previous items do not receive the acti ...

Include parameters in the function so that it will only run if the value matches a name in the provided

Let's start with an object: const oData = { name: 'Dragon', weapon: 'fire-breath', likes: 'Gold, Flying, Power', dislikes: 'Ice, Humans, Knights' }; This object is then passed to the following func ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

"Troubleshooting: React Bootstrap Modal not appearing on screen

I am facing an issue with rendering a Bootstrap modal in my React app when a button is clicked. Here is the code snippet for my React app: import React, { Component } from 'react'; import { Grid, Row, Col, Button, Table } from 'react-boots ...

The function is not able to fetch the value from the Amazon S3 file, however, it is printed

Despite troubleshooting methods such as declaring the variable outside the function and attempting to return it from the function, the below code is still not returning the Amazon S3 content. It seems to work when logging the data value on the console. ...

Having trouble parsing FormData in the django backend

Greetings everyone! I hope you are all doing well. I've been working on a custom form that needs to be sent to the Django backend using an AJAX request. The challenge I'm facing is that when I wrap the form into FormData, it works fine on the fro ...

React Apollo - Component not re-rendering when result changes

I am currently utilizing React Apollo to interact with a GraphQL backend. The function I am developing enables users to modify the admin permissions of another user. Within my setup, there are two components involved. One component houses the React Apollo ...

How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so: {{ myDate | date }} {{ myMoney | currency }} But, is there a way to dynamically set the filter type in a more flexible manner as shown below? // controll ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

How can I retrieve the children of a component in React?

Currently, I am working on implementing Class Components for a project involving a main picture and a smaller pictures gallery stored in an array. The overall structure consists of an all pictures container that houses both the main picture and smaller pic ...

Protected node.js REST API

I want to ensure the security of a restful API and aim to keep it simple and stateless. What is the best way to store, generate, and authenticate API keys? I was considering using node-uuid to generate keys, storing them in Redis, and then authenticating ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...