Mark Löwe
Mark Löwe

Reputation: 582

Passing a JavaScript function without executing

I have a callback without parameters and it stored in an object with no execution like so:

{callback:function(){ do my thing }}

Then I realized I needed to send in some parameters, and all the sudden JS is executing the function upon discovery:

{callback:(function(e){ do my thing with e })(event)}

Is there a way to do this without it executing immediately?

Upvotes: 3

Views: 4177

Answers (2)

Morgan T.
Morgan T.

Reputation: 1937

It's executing due to the parentheses here - (event)

This parameter is defined in the function declaration - function(e)

You need to pass this parameter wherever your client code is executing the callback, e.g.

if(thisCondition) {
    callback(event)
}

Upvotes: 0

marteljn
marteljn

Reputation: 6516

The problem is in your second snippet you are invoking the function with (event).

You should just be able to remove it and when the callback is executed, if an event is passed to the callback it will be e:

{callback:function(e){ do my thing with e }}

Upvotes: 4

Related Questions