Search code examples
javascripteventsmootools

Javascript double event firing unwanted


I want to perfom the same action for 2 different events firing. The problem I have is that one of the event fire the other. I'm using javascript and Mootools, also events are set on an 'input' element, which is inside a td cell.

I want to fire action 'save' when the element looses focus (onBlur) AND also when the user presses 'Enter' Key (onKeypressed). The problem comes from that the "save" action fire itself the 'onBlur' event. So when I press 'enter' save action is perfomed 2 times and it creates an unwanted behavior from the script.

Here's the 'save' function ('this' stands for the input elem)

storeUpdt(this); this.getParent().appendText(this.value); this.getParent().addEvent(....); this.destroy();

So if you have any idea, thank you !


Solution

  • You can always use a mutex to block the second event handler.

    function fireSave(event) {
      if (this._saving) {
        return;
      }
      try {
        this._saving = true;
        // do whatever stuff
      }
      finally {
        this._saving = false;
      }
    }
    
    function onKeyPressed(event) {
      // make sure the pressed key is ENTER
      fireSave();
    }
    
    var input = document.getElementById('whatever_input_id');
    input.addEventHandler('blur', fireSave, false);
    input.addEventHandler('keypressed', onKeyPressed, false);