François MENTEC François MENTEC - 1 month ago 6
Javascript Question

Javascript - How to not overwrite a var when used in a function passed as parameter?

I got a for loop and inside it a var named path, I use this var in a function that I pass as parameter of another function, it's look like this :

for( ... ){
var path = ...;
$("<button>").html(path).click(function(){ ...want to use path here... }).appendTo(...);
}


The problem is that path is overwritten at each new turn of the for loop, my full function look like this :

this.goTo = function(path){
that.path = path;
that.files = [];
that.selectedFiles = [];

//Display path
that.pathDiv.empty();
var dirs = that.path.split("/");
if(dirs.length > 1 && dirs[dirs.length-1].length == 0){
dirs.splice(dirs.length-1, 1);
}
for(var d in dirs){
var path = "/";
for(var i=0;i<d;i++){
if(dirs[i].length > 0){
path += dirs[i] + "/";
}
}
var name = "/";
if(dirs[d].length > 0){
path += dirs[d] + "/";
name = dirs[d];
}
that.pathDiv.append($("<button>").html(name).click(function(){ console.log(path); that.goTo(path); }));
}

that.directoryContent.empty();
serverUI.emit("getDirectoryContent", {path: that.path});
}


I can't use the onClick attribute in my html tag because I need to access to the object which triggered the function (that), any idea ?

Answer

You could attach the path as an attribute on the element itself, like so.

for( ... ){
  var path = ...;
  $("<button>").attr("path",path).html(path).click(function(){  
     $(this).attr("path")  // use it like this.
 ...want to use path here... }).appendTo(...);
}
Comments