0

Is there a way to do something like this?

//in file 1
function foo(val1, callback){
    callback(bar(val1)); //this will through an error
    //callback(bar); is the proper way, but then I'm not passing val1 (and I need to be able to set val2 inside the file 2 callback)
}

function bar(val1, val2){
    console.log(val1, val2);
}

//in file 2
foo('value1', function(bar){
    bar('value2');
});

and have that log: value1 value2?

I know I could just pass val1 into the callback, and then pass it again as bar(val1, 'value2'), but I'm wondering if there is a way to automate passing val1 instead of passing it manually. The file 2 function foo is going to be run a lot, and it would be nice to not have to pass the same parameter every time I want to run bar()

SwiftNinjaPro
  • 117
  • 1
  • 7

2 Answers2

0

I am not a javascript expert, but I found something similar here:

https://stackoverflow.com/a/13286241/12380678

Maybe it will help.

If it is not the case or you have already read that, then sorry for wasting your time.

Domino
  • 124
  • 5
0

I think I found something here

this answer suggested having the function return another function. this seems to work.

//in file 1
function foo(val1, callback){
    callback(bar(val1));
}

function bar(val1){
    return function(val2){
        console.log(val1, val2);
    };
}

//in file 2
foo('value1', function(bar){
    bar('value2');
});

method 2: using .bind (found on the same link)

//file 1
function foo(val1, callback){
    callback(bar.bind(this, val1));
}

function bar(val1, val2){
    console.log(val1, val2);
}

//file 2
foo('value1', function(bar){
    bar('value2');
});
SwiftNinjaPro
  • 117
  • 1
  • 7