zengod
zengod

Reputation: 1174

How to pass a variable reference to a function in JavaScript?

Suppose I have the following react-native code, in which I want the "press" function to be different based on the value of bProps.type:

const press = bProps.type > 0 
    ? props.function1(arg1, arg2) 
    : props.function2(arg1, arg2);
return <Button onPress={press}></Button>;

But the problem is that both function1 and function2 seem to be called before pressing the buttons, and pressing the buttons doesn't seem to call these functions. Is there a way I can set the value of "press" so that pressing the buttons calls the right functions?

Upvotes: 1

Views: 60

Answers (3)

Max
Max

Reputation: 1048

You can try this:

const press = bProps.type > 0 ? props.function1 : props.function2;
return <Button onPress={() => press(arg1,arg2)}></Button>;

Upvotes: 0

user47589
user47589

Reputation:

You can try this:

const press = bProps.type > 0 
    ? () => props.function1(arg1, arg2) 
    : () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;

The original code had to evaluate function1 and function2 before it could evaluate the ternary operator. Wrapping them in lambdas means the lambdas need to be evaluated, but that doesn't mean they are immediately called.

Upvotes: 0

Quentin
Quentin

Reputation: 943142

Currently you are calling the function and assigning its return value to press.

You need to create a new function (which will call the function you want to call with arguments when it itself is called by the event being triggered).

const press = bProps.type > 0 
    ? function() { props.function1(arg1, arg2) }
    : function() { props.function2(arg1, arg2) };
return <Button onPress={press}></Button>;

or

const press = bProps.type > 0 
    ? props.function1.bind(null, arg1, arg2) }
    : props.function2.bind(null, arg1, arg2) };
return <Button onPress={press}></Button>;

or

const press = bProps.type > 0 
    ? () => props.function1(arg1, arg2)
    : () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;

Upvotes: 3

Related Questions