Reputation: 4183
I am using JavaScript with HTML5. When the user clicks on a button, an event-driven JavaScript function starts up. When the user clicks on the button again, another instance of this function starts up. So I have two instances of the same function handling a event. However I only want the new instance to be running. How do I end the first instance of the?
An example is a function with the following code
Canvas.paper = Raphael(xOffset,yOffset,imageWidth,imageHeight);
masterBackground = Canvas.paper.rect(0,0,imageWidth,imageHeight);
window.onkeydown=function(e){
// Event handler code
}
document.addEventListener('keydown', function(event) {
// Event handler code
}
masterBackground.mousemove(function(e){
// Event handler code
}
Upvotes: 0
Views: 1038
Reputation: 474
If you want to make sure a function only runs once:
example based on benny's example
function onlyOnce(proc){
return function () {
var result = proc.apply(this,arguments);
proc = function () {};
return result;
}
}
Upvotes: 1
Reputation: 3394
var buttonView = document.getElementById('buttonView');
buttonView.handleEvent = function(event) {
window.alert(this.id);
//this.onclick = null;
};
buttonView.onclick = buttonView.handleEvent;
Try it out: http://jsfiddle.net/KHQ4y/
Edit: I posted this before you supplied your specific code, but you get the idea.
Upvotes: 1
Reputation:
Seems apparent that something asynchronous and long-running is happening.
To prevent concurrent instances from running, just use a flag that is set when one starts so that others can't begin. Then when the current one finishes, reset the flag so that another can start.
// Immediately invoked function, makes a variable and returns the handler
// that uses the variable as a flag.
button.onclick = (function() {
// local variable, only accessible to the returned handler
var running = false;
// This is your event handler.
return function(e) {
if (running === false) {
running = true;
// run your asynchronous operation
// after it's complete, set `running = false;`
}
};
})();
Upvotes: 1
Reputation: 5929
There are several solutions to this, some of them library dependent, but "nicer" to look at:
For example, using jQuery:
<button>Click me</button>
<script>
$('button').on('click', handleButtonClick);
function handleButtonClick() {
$(this).off('click', handleButtonClick); //disable click event
//do various things you don't want duplicated
$(this).on('click', handleButtonClick); //reattach handler
}
</script>
OR:
<button>Click me</button>
<script>
$('button').once('click', handleButtonClick); //attach one-time handler
function handleButtonClick() {
//do various things you don't want duplicated
$(this).once('click', handleButtonClick); //attach one-time handler
}
</script>
Most libraries support similar methods, if you'd rather do it vanilla JS, that is definitely possible of course as well. "am not i am" provided a nice example for that: https://stackoverflow.com/a/15976888/622129
Upvotes: 1