2

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
  • Just remove the var before dirty = false. Commented Oct 12, 2010 at 19:33

4 Answers 4

5

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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...

Comments

2

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(){

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.