• 0

Javascript/jQuery - Passing inline function as arg to another function


Question

Having a really hard time getting this to work, could use a little guidance on what I'm doing wrong....the code should be fairly self explanatory....the $.get isn't important, just an example with some asynchronous execution to demonstrate the point of this function, but it could be anything at all, don't focus on that please :)

function callbackTest(file, callback)
{
    $.get
    (
        file,
        function(data)
        {
            // do something
            callback.call(data);
        }
    );
}

Then call it like.....

$(document).ready
(
    function()
    {
        callbackTest
        (
            "file.html",
            function(data)
            {
                alert(data);
            }
        );
    }
);

When I try this, I get an error from the callbackTest function, "callback is not a function".

Obviously this isn't the correct way to do what I want (or it would work!), but it should be pretty clear from this exactly what I'm trying to achieve. Any help at all would be appreciated.

Cheers.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Not sure as to why your getting that specific exception, but your use of Function.call is wrong, the first argument overrides "this", so you need to make sure you call it either:

callback(data);

...or:

callback.call(this, data);

...or:

callback.apply(this, [data]);

Link to comment
Share on other sites

  • 0

Not sure as to why your getting that specific exception, but your use of Function.call is wrong, the first argument overrides "this", so you need to make sure you call it either:

callback(data);

...or:

callback.call(this, data);

...or:

callback.apply(this, [data]);

I'd already tried callback(data), and now also tried the other two suggestions, same error from firebug, the callback function is never called.

Link to comment
Share on other sites

  • 0

Please disregard, I'm an idiot.

I was using a somewhat more complex version of this, edited from a synchronous version of my function, and I had left in an extra param, duh.....

Sorry!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.