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?