Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The solution to this problem depends on how and where you use those two functions. If you pass them as callbacks to another function from some ajax library, or something like that, and if you control that library call, you could use a closure.</p> <p>So, if for example you do something like this when an upload is begun:</p> <pre><code>Library.foo(..., uploadstart, uploadfinish); </code></pre> <p>You could define makeID as a global function, and then bind the generated id to your callbacks using a function like this:</p> <pre><code>function bind_id(rand_id, my_function) { return function() { // return a closure return my_function(); // my_function is executed in a context where rand_id is defined } } </code></pre> <p>Then you define your callbacks using rand_id as if it were global (actually, it will defined in the closure):</p> <pre><code>function uploadstart() { // use rand_id as you wish } function uploadend() { // use rand_id as you wish } </code></pre> <p>When you need to call your Library.foo function, first generate the rand_id, then bind it to the start and end callbacks:</p> <pre><code>var new_rand_id = randID(); Library.foo(..., bind_id(new_rand_id,uploadstart), bind_id(new_rand_id,uploadend)); </code></pre> <p>This way you'll pass to foo not the original uploadstart and uploadend, but two closures where rand_id is defined and i the same for both, so that callback code can use that variable.</p> <p>PS: closures are one of the most powerful and trickiest features of javascript. If you're serious about the language, take your time to study them well.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload