Scopes

Unlike traditional client side javascript which has one global scope, a 10gen application has multiple global scopes. One key thing to remember is that when one invokes a file local.model.student() it is equivalent to a function call. Thats means the student file has its own local scope, and access to the scope in which it was invoked.

Context Scope

When an instance of an application starts, there is a scope created for the instance - which we call the Context scope. This is the scope that _init.js is called in. This scope is created when the application starts, and dies when the application is either restarted or killed. There is no synchronization across servers. The Context scope is really only meant for storing libraries and functions so that you only have to load them once. If you want to persist things, they should be stored in the database.

Request Scope

Every request that your application handles will get its own global scope. This scope will have the Context scope as its parent. When you are handling a request, you will be able to read things from the Context scope, but not add or remove things. You will be able to modify properties of objects that are already in the scope.

If in your _init.js you have

foo = 2;

in an index.jxp file you could do

<%= foo %>
and it will obviously print 2.

<% foo = foo + 2; %>
<%= foo %>
The first time it will obviously print 4. The interesting thing is that it will always print 4 because you can't modify the Context scope, so the new value of foo just goes into the request scope.

if in _init.js you had

<%= data.foo = 2; %>
and worked off of that, it could increment forever.

Every request scope is destroyed when the request is finished.

Interaction with _init

As described in more detail in the lifecycle article, when a directory is first accessed, if there is an _init.js file in the directory, it will be invoked. When the _init file in any directory is invoked, it is invoked in the Context scope. This enforces the idea that _init is meant to be called once, and is a good place to load libraries and other files that should just be loaded on startup.

An interesting side effect of loading files from _init.js is that they get defined in the Context scope. So the question is if you set a global variable from a function defined in the Context scope, where does it go. We've decided that it makes the most sense to go into the request scope. That means that even though you define a function in the Context scope, it still behaves as if it were defined in request scope.

If you have this in your _init.js

foo = 2;
myFunc = function(){
   foo = foo + 2;
   return foo;
}

and an index.jxp with

<%= myFunc() %>
it will always print 4.

See Also