Is JavaScript overwriting the existing value?

I am completely new to JavaScript and I am struggling with a seemingly simple issue. I have an array of usernames that I am iterating over. My goal is to map these usernames to click event methods, although I am aware that this may not be the most efficient approach:

this.events = this.events || {};
var self = this;

for (var i=0; i<arr.length; i++) {
    console.log(data.user[i]);    // < --- this username is correct
    var username = data.user[i];
    $(this.el).append("<td><button class='btn btn-primary save" + i + " btn-sm'>Save</button></td>");

    var eventKeySave = 'click ' + '.save' + i;
    this.events[eventKeySave] = function(){
            (function (username) {
                console.log("inside method save " + username); // <--- this username is wrong
                self.onSave(username, 'something')
            })(username);
        };
}

this.delegateEvents();

In my onSave method, all it does is print the usernames:

onSave: function(name, extras) {
    console.log("you clicked save on " + name + " , " + type); // < -- wrong name
}

But no matter what, I always end up getting only the last username of the array in my onSave function.

For example, if my array looks like

[ 'david', 'emily', 'stephanie', 'michelle']
, only michelle is passed into the onSave function, even though each button's click event should have been associated with the respective name in the array.

I even attempted to pass the username by value, but it still did not work. What could be happening in JavaScript that I am missing?

Answer №1

Implementing a closure is necessary in this scenario:

this.events[eventKeySave] = (function (name) {
    return function(){
        console.log("inside method save " + name); // <--- this username is now ok
        self.onSave(name, 'something');
    };
})(username);

This issue arises because the function is invoked after the for loop concludes, causing the "username" variable to hold the last value from the array in all cases. By introducing a closure, the actual value of 'username' is preserved for the returned function.

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

Preserving the true IP address when initiating cross-domain requests

Initially, I tried creating a reverse proxy using Express to enable forwarding requests from localhost:3000/request to somesite.com/request. Here is the code snippet I used: var request = require('request'); app.get('/', function(req, ...

Deleting parentheses within a NodeJS string

I am working with a variable in Nodejs that contains data within square brackets. My goal is to remove the square brackets and extract the actual value from it let value = "[dfsdf][dsfsd][sdfs]MY VALUE"; The value I need to retrieve from the var ...

Utilize the JSON response upon successful completion of an AJAX request

I'm currently working with this code snippet: function openIzmeni(value) { $.ajax({ url: "getRzaizmenu.php", type: "POST", async: true, data: { vrednostid:value}, //your form data to post goes here as ...

Guiding you on exporting a Typescript class with parameters in Node.js

Trying to find the Typescript equivalent of require('mytypescriptfile')(optionsObject); This is the TS code provided: export class Animal { name: string; public bark(): string { return "bark " + this.name; } constructor(color:string) ...

Running an express server on localhost with nginx: A step-by-step guide

Is it possible to run the express server using Nginx on localhost? And if so, how can this be accomplished? const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Hello ...

Divide information in the chart

<table id="tab"> <tr><td class="sub">mmmmm</td><td class="sub">jjjjj</td></tr> <tr><td class="sub">lllll</td><td class="sub">wwwww&l ...

Reflections on the Javascript Prototype Design Pattern

After using a Javascript revealing module pattern, I'm now transitioning to a new approach which seems to be working. However, I'm not entirely sure if I'm following the best practices. Specifically, I want to know if my method of preserving ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates. app.use(function (req, res, next) { res.locals.currentUser = req.session.userId; next(); }); When logged in, I can access the id. However, when not logged in, t ...

Can JavaScript be used to mimic selecting a location from the autocomplete dropdown in Google Maps API 3?

Currently, I am attempting to automate the process of selecting items from the autocomplete dropdown in the Google Maps API v3 places library using jQuery. However, I am facing difficulty in identifying the necessary javascript code to select an item from ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...

find all occurrences except for the last of a pattern in javascript

When considering the patterns below: "profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]" It is possible to extract the last part by utilizing non-capturing groups: var rege ...

Leveraging Vue.js's computed properties to access and manipulate elements within an

I have a simple template that displays text from a wysiwyg editor using two-way data binding, as shown below: <template> <div> <quill-editor v-model="debounceText" :options="editorOptionProTemplate" > </qu ...

The file-loader is able to organize images into separate folders when saving them. For example, an image file named "example.jpg" located in Project/Module

Hey there! I'm currently in the process of setting up a Webpack configuration that will generate files for each folder within my project. Unfortunately, creating a separate webpack.config file for each folder is not an option. So far, I have successf ...

Adding one class at a time, with each new class being added every second

My goal is to add classes one by one [test0 test1 test2] up to 10, with each class being added after one second. $('.rating-block').AddClass('test0 test1 test2 ... test10' ); I am experimenting with the following code, but I don' ...

Enhancing user experience with jQuery tooltips

Having trouble adding a tooltip to a glyphicon. The JSFiddle example provided does not work for me as I am using jQuery to create the HTML elements like this: var trashIcon = $('<i>').addClass('glyphicon glyphicon-trash'); How ...

Finding an element based on its styling attribute, such as its position on the left or right side

One particular block that caught my eye is the slider element: <div id="sliderDispo" class="slider slider-dispo" data-slider-init="" data-slider-color="#0077b5 #EC6E31 #E40B0B" data-slider-step="33" > <div class="slider__interval" ...

Can we achieve live map updates in real time using Google API with Node.js technology?

Can Google Maps API in conjunction with Node.js provide truly real-time updates on a map without any callback limits, or does Google enforce restrictions such as a 5 second or 30 second time frame? Node.js is known for its ability to handle almost real-ti ...

Having trouble getting the code to properly execute a PHP file when a button is clicked

I'm facing an issue with a button on my page. When I click on the button, jQuery-AJAX is supposed to execute PHP code from another file, but it's not working as expected. The button's code is very simple: <button type="submit" onclick=" ...