views:

52

answers:

4

We have three JS files:

<script type="text/javascript" src="js/pm.init.js"></script> 
<script type="text/javascript" src="js/pm.util.func.js"></script> 
<script type="text/javascript" src="js/pm.nav.js"></script> 

In init.js we have:

$(function(){
    var dirty = false;
})

In util.func.js we have:

function dirtyCheck(actionFunction) {
    if (dirty == false) {
        actionFunction();
        return;
    }
    ...

And in nav.js we have:

$(function(){
    $('#btn-nav-refresh').click(function() {
        dirtyCheck(function() { doRefresh(); });
    });
    ...

Now when the btn-nav-refresh function fires after a user clicks the button we get a dirty is not defined error. Why is this??

+1  A: 

In init.js can't you just put var dirty = false; as a global variable and not inside a function definition?

Crackerjack
+1  A: 

The variable dirty is only known in your closure. That's why.

$(function(){
    var dirty = false;
});
alert(dirty); // Undefined (same file, just one line after.

It's the main feature of the closure...

Arnaud F.
+3  A: 

I feel dirty myself telling you how to make your "dirty" variable into a dirty global variable, but it'd be like this:

$(function(){
  window.dirty = false;
})

You should however find a better way to do this. Here's an idea:

$(function() {
  $('body').data('dirty', false);
});

Then:

// ...
if (${'body').data('dirty')) takeBath();
Pointy
+1  A: 

As others have noted, dirty is out of scope because it is enclosed by your document ready function. Change your declaration to be like this instead:

var dirty = false;
$(function(){

});
Ender