3

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?

2
  • 2
    Well, that's a Immediately Invoked Function Expression, so no. Any reason why you need to use an IIFE in this instance? Commented Oct 9, 2013 at 13:15
  • If you are needing some values for setup of your function just close over them. Your function can access them and you have no need to pass them in. Commented Oct 9, 2013 at 13:17

2 Answers 2

4

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 }}
Sign up to request clarification or add additional context in comments.

3 Comments

This definitely stops the execute problem, and is exactly how I started, however the parameter doesn't have a value. It's undefined upon execution. :( I should clarify, and perhaps this is my problem: I have e in memory at the moment of saving it to the callback variable in hopes that it will preserve in a future execution.
@MarkLöwe you are going to have to provide more code in order to troubleshoot that issue. However, based on your comment, you are going to need to maintain a reference to your event object in a closure.
I'm attempting to create a dynamically generating callback "creator" if you will. I have a generic system that registers a callback array using parameters that I'm passing in. So I only have possession of the values at the point of adding to them to object array. So the function(e){ do something with e) loses its "e" by the time I need to call it. The method of appending the value with (e) at the end works, but causes JS to execute the function right away. I think my answer is to store the parameters in the array, and shove them into the function upon execution.
0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.