1

I'm using jqlight(similair to jquery but it doesn't have $document.data('events')) to bind a keypress to document.

    $document.bind('keypress', function(event){

I add bind the key press when a checkbox is checked, like this:

if(onScreenData.getChecked().length > 0){
  $document.bind('keypress', function(event){
else{
  $document.unbind('keypress');
}

where onScreenData.getChecked().length is the number of checkboxes.

I want to only bind the keypress when the number of checked checkboxes goes from 0 1.

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • Wouldn't you know already since it is your site and your code? – Huangism Mar 20 '14 at 13:01
  • possible duplicate of [How to check if click event is already bound - JQuery](http://stackoverflow.com/questions/6361465/how-to-check-if-click-event-is-already-bound-jquery) – Huangism Mar 20 '14 at 13:03

2 Answers2

3

Why do you want to bind and unbind the keypress event? Far more efficient is to always bind it but check the number of checkboxes on the page in your event handler right away and return out of it right away if you need to.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
2

You could always unbind it, and only bind when you want

$document.unbind('keypress');
if(onScreenData.getChecked().length > 0){
     $document.bind('keypress', function(event){ /* ... */; })
}

You could also do this, but this should be considered as a workaround:

if( $document.attr('data-has_keypress')=='true'){
    $document.unbind('keypress');
}
if(onScreenData.getChecked().length > 0){
     $document
         .bind('keypress', function(event){ /* ... */; })
         .attr('data-has_keypress', 'true');
}

Also: how to check if element has clickhandler

Community
  • 1
  • 1
Martijn
  • 15,791
  • 4
  • 36
  • 68