tags:

views:

1185

answers:

4

I am having problem with the following javascript -

var bVisited = false;

function aFuncCallBack(somestring)
{
    bVisited = true;
}

processingManager.setCallBack(aFuncCallBack);
processingManager.DoWork();

if(bvisited == false)
    alert("Call back not entered");

aFuncCallBack gets hits in my case; I am setting the bVisited to true there - but still when I check the variable after the DoWork call the value is still false - I am not able to figure what the problem is. I searched for some threads but didn't find anything relevant.

Could someone throw some light on why this behavior and possibly what should I do?

Thanks.

+3  A: 

Does the callback run asynchronously? Try adding an alert() into the callback and see if it fires before your existing alert.

If there's some weird scope thing going on (shouldn't be, but you never know) you can access globals using the window object: window.bVisited = true;

Edit: You check bvisited == false instead of bVisited == false - hopefully that's a typo in your question and not in the code!

Greg
+3  A: 

If processingManager.DoWork(); is asynchronous it is possible that it can return before bVisited has been set.

Also, you have bvisited in your test, not bVisited -- is that a cut&paste from your code?

Brian C. Lane
A: 

As the others pointed out, JavaScript is case sensitive, and undeclared variables are undefined, ie. 0/false/null by default.
A common gotcha with dynamic languages without something like use strict/option explicit or similar directives...

PhiLho
A: 

sorry , its actually a typo on bvisited - and my question was really about storing the states -

i kind of figured out the problem for myself after i posted this question - the problem is due to asynchronous calling -

as someone pointed out -

> If processingManager.DoWork(); is asynchronous it is possible that it can return before bVisited has been set. >

yes, processingManager.DoWork is an asynchronous call - and my js is running to completion before bvisited is set to true through a call back -

so - that creates another doubt in me - are global variables visible across all the js files ? meaning that say, as a part of my execution, i have two js files -

1.js
//CODE bVarGlobal1 = true //CODE

first 1.js is executed and then 2.js will be processed

here, can 2.js access the bVarGlobal1 variable in any way ? (do we need to prefix any "export" kind of keyword to the bVarGlobal1 variable in the 1.js so that the variable is visible through out the life time of the execution of the program ?)

PS: i am from C/C++ background and new to javascript so pardon me about the "export" keyword if such a thing doesnt exists in JS :)

naiveCoder
You may want to ask this as a separate question, but the short answer is yes, everything in file 1 will be visible in file 2.
Benry