Вопрос

I’m trying to prevent a click handler from firing based on a condition inside the mousdown handler for the same element. Consider this:

var bool = true;

$('button').click(function() {
  console.log('clicked');
}).mousedown(function(e) {
  bool = !bool;
  if ( bool ) {
    // temporary prevent the click handler, how?
  }
});

Is there a neat way to cross-communicate between handlers? Here is a bin: http://jsbin.com/ipovon/1/edit

Это было полезно?

Решение

This works, although, I'm not sure it's quite the answer you were looking for. It's basically a double click function, if you set bool=false; initially.

var bool = true;

$('button').mousedown(function(e) {
  bool = !bool;
  if ( bool ) {
    $(this).unbind('click');
  }
  else
  {
    $(this).click(function(){
        console.log('clicked');
    });
  }
});

Update

Also, you could pull the click function out of the mousedown like this, if you like:

var bool = true;
function buttonClick(){
  console.log('clicked');
}
$('button').mousedown(function(e) {
  bool = !bool;
  if ( bool ) {
    $(this).unbind('click');
  }
  else
  {
    $(this).click(buttonClick);
  }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top