Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - resetting a variable

I have a variable in a web page that gets set to a value and is of type string. When a button is clicked, it calls a function & at the end of the function, I would want to clean up anything that had been set previously. I have tried using:

$.removeData(myVar);

but it doesn't do anything. Log statements before & after that statement show that it still has the value & type both before & after the above statement.

Another unused variable has a value of undefined and a type of undefined. Both these variables happen to be global variables in the page.

How do you reset myVar to its initial state? I know it ought to be simple, but I'm missing something. Would appreciate any help.

like image 438
steve_o Avatar asked Dec 18 '13 22:12

steve_o


2 Answers

Well...several possible direct answers.

myVar = undefined;
myVar = null;
delete window.myVar;

HOWEVER, I would question the logic of having the variable be global, but only be used in certain methods. Here's how it might be better to structure (with a random pseudo-example of adding up values from ajax):

addAjaxButton.onClick(function() {
  var counter = 0;
  ajax(function(addition) {
    counter += addition;
    ajax(function(moreAdd) {
      counter += moreAdd;
      alert('Total is ' + counter);
    });
  });
});

In that case, counter doesn't need to be deleted - it will just go out of scope when all AJAX is complete.

like image 168
Katana314 Avatar answered Oct 19 '22 22:10

Katana314


Just assign a value to it. If the initial state was undefined, set it to null. You don't have to do anything fancy with jQuery to kill the value.

like image 25
Bic Avatar answered Oct 20 '22 00:10

Bic