views:

27

answers:

1

Hi, I want to execute a function that is inside the jquery document ready closure. But I want to execute it from a global context.

e.g.

$("document").ready(function () {
    function myFunction() {
        alert("test");
    }
});

Is there some sort of "path" syntax I can write, to get inside the doc ready closure?

e.g. Here is some pseudo code (I've made this synatx up):

document.ready.myFunction();

You might be wondering why I wish to do this; the reason is so I can execute functions from a javascript console (e.g. the console in IE developer toolbar / firebug etc) that are inside the "ready" function closure.

+1  A: 

In short, you can't, they're just not accessible...this is one of the core functions of closures. If you want it available outside, you either need to declare it outside, like this:

function myFunction() {
    alert("test");
}
$(document).ready(function () {
  //something..
});

Or define it as a global variable inside (though I don't see a lot of sense in this, unless you have some other references going on):

$(document).ready(function () {
    myFunction = function() {
        alert("test");
    }
});

To define a function and execute it on document.ready, it can be as simple as this:

function myFunction() {
    alert("test");
}
$(myFunction);

This leaves it accessible and executes it once on document.ready, not sure if that's what you're after but it is an option.

Nick Craver
Thanks Nick, that is what I guessed. I'm debugging existing code and don't really have the luxury of altering it.
Alex Key
@Alex - Is taking the output and testing elsewhere, e.g. [jsfiddle](http://jsfiddle.net/) an option?
Nick Craver
@Nick, jsfiddle looks interesting - thanks for going the extra mile to help :-)
Alex Key