StudioTime
StudioTime

Reputation: 23989

Load a function which is out of scope

I have a page which loads a file at the top of itself containing most of my JQuery functions.

So within the file is e.g.:

$().ready(function() {
  function foo(){
    doSomething;
  }
}

Now, at the end of that particular page I want to use one of the functions in the file loaded previously.

When I call foo(); it says foo is not defined which I get, my question is can I call that function? And if so how?

I also tried:

window.onload = function(e){
  foo();
}

but same error

Upvotes: 1

Views: 150

Answers (4)

Alnitak
Alnitak

Reputation: 339856

If (and that's a big if) foo needs to be called in global scope, then simply declare it in global scope - there's no point hiding it away as an inner function of $().ready if that's not where it's going to be used.

If you want to avoid global pollution, wrap the whole thing in an Immediately Invoked Function Expression:

(function() {

    // called when all resources are loaded
    window.onload = function foo() {
        ...
    }; 

    // called when the DOM is ready
    $().ready(function() {
        ...
    });

})();   // invoke now

Upvotes: 1

Raphael Serota
Raphael Serota

Reputation: 2197

You'll have to define foo where it is globally accessible. Instead of function foo(){} try window.foo = function(){}.

A slightly less sloppy approach than sticking a bunch of properties on the window object would be to define one global object where you put things, e.g.

var myApp = {};

$(document).ready(){
    myApp.foo = function(){ doSomething; }
}

This way, scripts that execute later on the same page will have access to myApp.foo.

Upvotes: 1

chfumero
chfumero

Reputation: 1147

The problem here is that you are declaring the function inside the scope of the anaonymous functions passed to the ready jQuery method.

$().ready(function() {
  function foo(){
    doSomething;
  }
// foo can only be accessed on this scope.
});

You can just expose the function to the window scope using the window variable.

$().ready(function() {
  window.foo = function foo(){
    doSomething;
  }
// foo can be accessed on this scope and on the gloabl app scope.
});

Upvotes: 1

hakazvaka
hakazvaka

Reputation: 733

Declare it in global scope.

var foofn;
$().ready(function() {
  foofn = function(){
    doSomething;
  }
})

Upvotes: 2

Related Questions