Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a global value (not necessarily a global variable) in jQuery?

Currently I am working on a legacy web page that uses a ton of JavaScript, jQuery, Microsoft client JavaScript, and other libraries. The bottom line - I cannot rewrite the entire page from scratch as the business cannot justify it. So... it is what it is. Anyway, I need to pollute (I really tried not too) the global namespace with a variable. There are the three options I was thinking about -

  1. Just store/retrieve it using a normal JavaScript declaration - var x = 0;

  2. Use jQuery to store/retrieve the value in a DOM tag - $("body").data("x", 0);

  3. Use a hidden form field, and set/retrieve the value with jQuery - $("whatever").data("x", 0);

Is there a better way? I looked at the existing pile of code, and I do not believe the variable can be scoped in a function.

like image 493
Kris Krause Avatar asked May 19 '10 15:05

Kris Krause


People also ask

How do you avoid global variables?

The simplest way to avoid globals all together is to simply pass your variables using function arguments. As you can see, the $productData array from the controller (via HTTP request) goes through different layer: The controller receives the HTTP request. The parameters are passed to the model.

Why is it not necessary to pass a global variable to a function?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

Why global variables are bad in JavaScript?

Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn't overwrite values of another variable.

Why is my global variable undefined?

The reason the first alert is undefined is because you re-declared global as a local variable below it in the function. And in javascript that means from the top of the function it is considered the local variable.


1 Answers

You can create a namespace inside the jQuery object, like so:

$.mynamespace = {      myVar : "something",      myVar2 : "somethingElse"  };  

or:

$.mynamespace = {}; $.mynamespace.myVar = "something"; $.mynamespace.myVar2 = "somethingElse"; 

Bear in mind, any plugin method named 'mynamespace' will be overwritten so be sure to use a sensible name.

like image 163
karim79 Avatar answered Sep 23 '22 04:09

karim79