PrimuS PrimuS - 3 months ago 8
Javascript Question

Pass function to function in Javascript calls 2nd function immediately

I have a function that accpets another function as a param:

Function Call

openDialog('warning',removeRowAction(id));


openDialog Function

function openDialog(type, action){
if(type == 'warning'){
action();
}else{
console.log(type);
}
}


removeRowAction Function

function removeRowAction(row){
$('#row_'+row).remove();
}


Unfortunately the
removeRowAction(id)
is called immediatley, no matter what
type
I have and even before the
if
.

Is what I want to do even possible?

Answer

The problem is that you're calling removeRowAction when you pass it to openDialog. You want a function that returns a function, like this:

function removeRowAction(row){
   return function() {
      $('#row_'+row).remove();
   }
}

openDialog('warning',removeRowAction(id));

This will let you use any id that you want anywhere in your code.