简体   繁体   中英

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.

var enterToggle = true;
function enterToggleListener(elem) {
  enterKeyPress();
  elem.click(function() {
    enterToggle = !enterToggle;
    console.log('enter-toggle clicked')
    if (enterToggle === false) {
      console.log('enter toggle false')
      // What do I need to add here to stop 'enterKeyPress()'?
    } else {
      console.log('enter toggle true')
      enterKeyPress();
    }
  });
}

function enterKeyPress() {
  $('#noteText').keypress(function(e){
    if(e.which == 13){
      $('#noteButton').click();
    }
  });
}

enterToggleListener($('#toggle-button'));

What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?

EDIT: Cleaned-up code, with @James Montagne's answer added

var enterToggle = true;
function enterToggleListener(elem) {
  elem.click(function() {
    enterToggle = !enterToggle;
    if (enterToggle === false) {
      $('#enter-toggle').text('Enter key saves note (OFF)')
    } else {
      $('#enter-toggle').text('Enter key saves note (ON)')
    }
  });
}

function enterKeyPress() {
  $('#noteText').keypress(function(e){
    if(enterToggle && e.which == 13){
      $('#noteButton').click();
    }
  });
}

enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
    $('#noteText').keypress(function(e){
        if(enterToggle && e.which == 13){
            $('#noteButton').click();
        }
    });
}

You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.

However, if you must add and remove for some reason, you would use off .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM