BonsaiOak
BonsaiOak

Reputation: 28941

Run code in function as if it were running in another scope

I'm following some example code for a Node.js-based music player. The example just has the player play some files passed on the command line:

for (var i = 2; i < process.argv.length; i += 1) {
  batch.push(openFileFn(process.argv[i]));
}

I want to change it so that the code to play something only is run when another event happens. I tried to do this by wrapping the above code in a function and calling it from my event handler. Unfortunately, nothing happens when I do it that way:

function play() {
  for (var i = 2; i < process.argv.length; i += 1) {
    batch.push(openFileFn(process.argv[i]));
  }
}
play(); // Works

function eventHandeler() {

  // Other code
  play(); // Doesn't work!
}

I have verified that the play function is getting called by setting breakpoints in my debugger, so the only other thing I can think of is that the function is somehow getting messed up by changed scope. How can I call play() in the desired scope?

Here's a GitHub gist with all the code: https://gist.github.com/anonymous/01f9572e73cdf3103e7b

Upvotes: 0

Views: 74

Answers (1)

jfriend00
jfriend00

Reputation: 707318

There's no issue calling a function like play() from a lower scope. The function is reachable in both cases. So, this is not purely about scope.

So, the issue is more likely one of timing and the state of other variables that the function depends upon. For example, the variable batch has to be in the appropriate state for your function play() to do what it is supposed to. My guess would be that either that variable or something that openFileFn() depends upon is not in the correct state when you make the second function call.

The usual way to solve this issue is to create functions that stand on their own and don't depend upon other global state or state in other scopes. If they create/initialize their own state or are passed state that they should use (or some combination of the two), then they can be called from anywhere.

Upvotes: 1

Related Questions