ekkis
ekkis

Reputation: 10226

Avoiding global scope?

I like to include my javascript in each page that needs it (more general js files go in the document head):

-- item.html --
<div id="item">
<script type="text/javascript" src="item.js"></script>
 ...
</div>

so in my script file I can now grab the container and use it to find things:

-- item.js --
var container = $('scripts').last().parent();
var f = container.find('form');

however, if the work needs to be done after the page loads:

$().ready(function() {
    var f = container.find('form');
});

I have a problem because container scopes across files. consider:

-- index.html --
<div id="item">
<script type="text/javascript" src="item.js"></script>
 ...
</div>
<div id="link">
<script type="text/javascript" src="link.js"></script>
 ...
</div>
<div id="part">
<script type="text/javascript" src="part.js"></script>
 ...
</div>

where the item.js fails because it picks up the last value container was assigned, instead of the one it was assigned at the time that it was declared such that it in essence performs:

$('#part').find('form');

instead of what I want:

$('#item').find('form');

so my question: how do I make the scope of container local to the file where it's declared?

alternatively, how could I do this differently?

Upvotes: 1

Views: 155

Answers (3)

kim3er
kim3er

Reputation: 6476

I don't a environment to test this on, but would this small alteration work?

var container = $('script[src="item.js"]').parent();

You would have to specify the filename for each scope, but that doesn't seem like much of a burden.

Upvotes: 0

therealklanni
therealklanni

Reputation: 652

Please look into modularizing your code using something like AMD to solve this. This is exactly what AMD was designed to solve.

There are several possible libraries for this. Since you are using jQuery, RequireJS might make the most sense, however there are other solutions as well, such as

Upvotes: 3

Norman Breau
Norman Breau

Reputation: 2417

JavaScript in the browser is functional scope. Which means variables declared (using the var keyword) belongs to the top most function, or the global scope if there is no function.

So to answer your question, in every file, you can do:

(function() {
    var someVariable = 1;
    //...
})();

What this does, is first evaluates and creates the anonymous function, and then immediately executes it with no arguments.

Since you are executing a function, any variables that you declare (as long as you use var), will be scoped to the function, and won't be available globally.

Upvotes: -2

Related Questions