tags:

views:

59

answers:

3

Hi,

I'm trying to use a closure (I think that's what it is..), I'd just like to execute a function with a local variable at some point in the future, like this:

function boo() {
    var message = 'hello!';
    var grok = function() { alert(message); }
    foo(grok);
}

function foo(myClosure) {
    $.ajax({
        timeout: 8000,
        success: function(json) {
            myClosure();
        }
    }
}

I could get around this by using global variables and such, but would rather use something like the above because it at least seems a bit cleaner. How (if possible) do you do this?

Thanks

----------- Update --------------------

Sorry I wasn't clear - I was wondering if this is the correct syntax for the closure, I tried it out and it seems ok. Thank you.

A: 

Is it what you want?

var boo = (function() {
    var message = 'hello!';
    return function() {
      foo(function() { 
        alert(message); 
      });
    };
})();

function foo(myClosure) {
    $.ajax({
        timeout: 8000,
        success: function(json) {
            myClosure();
        }
    }
}

or just

function boo() {
    $.ajax({
        timeout: 8000,
        success: function(json) {
            alert('hello!'); 
            // do sth with json
            // ...
        }
    }); // <- missed a paren
}

The example is too simple to know what you want btw.

galambalazs
-1 hi Pointy ... :)
galambalazs
A: 

Unless you actually want to make an AJAX call, setTimeout might be more along the lines of what you are looking for:

function foo(myClosure) {
    setTimeout(myClosure, 8000); // execute the supplied function after 8 seconds
}

If your question was more along the lines of "Am I creating a closure correctly?", then yes, your function boo is doing the right thing.

pkaeding
A: 

Your existing code looks perfectly fine except for that missing paren at the end. ;)

If you're looking to understand the concept of closures more deeply, think of it this way: whenever something in a closured language is defined, it maintains a reference to the local scope in which it was defined.

In the case of your code, the parameter to $.ajax() is a newly-created object ("{ timeout: 8000, etc. }"), which contains a newly-created function (the anonymous "success" function), which contains a reference to a local variable ("myClosure") in the same scope. When the "success" function finally runs, it will use that reference to the local scope to get at "myClosure", even if "foo()" ran a long time ago. The downside to this is that you can end up with a lot of unfreeable data tied up in closures -- the data won't be freed until all references to it have been removed.

In retrospect, I may have confused you more than helped you. Sorry if that's the case. :\

Faisal