Cratylus
Cratylus

Reputation: 54094

Most appropriate global variables in javascript?

I have a function that I execute when I press a button.
I don't want the user to execute the function twice in a row. So I used a window variable.
I did:

function a() {  
  if(window.infunction != undefined || window.infunction != null) {  
       return;  
  }  
  window.infunction = 'true';    
  //do stuff  
}  

Somewhere else (in another button press) I reset: window.infunction = undefined

Is this the proper way to use global variables (at least for my needs)?

Upvotes: 0

Views: 123

Answers (3)

user428517
user428517

Reputation: 4193

No, there's no good reason to use global variables for this. It's easy enough to just wrap all your code in a function to avoid polluting the global namespace:

(function() {
    //all your code here
})();

But I think a better solution would be to remove the event handler upon clicking the button instead. Here's an example:

HTML:

<button id="click_me">Click me</button>

JavaScript:

function click_function() {
    alert('You clicked the button with ID ' + this.id);
}

function click_listener() {
    click_function.call(this);
    this.removeEventListener('click', click_listener);
}

document.getElementById('click_me').addEventListener('click', click_listener);


Alternatively, some JS libraries make it easy to assign a handler that will only fire once. In fact, I highly recommend this: you won't have to type nearly as much code. For example, when using jQuery you can just write:

$('#click_me').one('click', function() {
    alert('You clicked the button with ID ' + this.id);
});

This does the same thing as the above code, except it's compatible with more browsers, including older versions of IE.

Upvotes: 3

claustrofob
claustrofob

Reputation: 4994

Functions are objects. They can have properties like any other objects:

function a(){
    if (a.executed) return;
    a.executed = true;

    //do stuff
}

As @Ian mentioned in his comment you can easy make the function reusable. It can be advantage as well as a downside of this approach.

And as @Dave said it can be achieved with closure:

var a = (function (){
    var executed = false;

    return function (){
        if (executed) return;
        executed = true;

        //do stuff
    }
})(); 

Upvotes: 3

Gabe
Gabe

Reputation: 50523

Disable the button or hide it so the user is not confused why the button does nothing after the first click.

function a(e) {
     e = e || window.event;
     e = e.target || e.srcElement;  
    // disable element
    e.disabled = true;
}


You should just unbind the event instead.

function a(e) {  
    // unbind the event
    e = e || window.event;
    e = e.target || e.srcElement;
    e.onclick = null;
}

Upvotes: 0

Related Questions