0

I'm binding some slightly complex functionality to a click event

$(someSelector)).bind('click', someFunction(a,b,c));

function somefunction(a,b,c) {
    return function() {
        // some logic
        $(anotherSelector).each(function() {
            // fade out with call back...
            $(this).fadeOut("fast", function() {
                // TODO: add callback here???
                $(contentSelector).fadeIn("fast");
            })
        })

    }
}

The problem is that a series of fast clicks results in inconsistent fadeOut / fadeIn behaviour. I'm assuming that new click events are processed before the current fadeIn is complete.

I think I'm looking for some callback mechanism that ensures that new clicks are processed after current clicks are finished. I could add a callback to fadeIn, but I don't see what I kind of logic would help me there...

I also read about unbinding components for as long as a click is processed (and later rebinding them), but again - I'm not sure on top of which logic I would put that.

Thanks for advice :)

Jan Groth
  • 14,039
  • 5
  • 40
  • 55

1 Answers1

1

You could utilize jQuery's .on and .off methods:

$someElement = $(someSelector)
$someElement.on('click', someFunction(a, b, c));

function someFunction(a, b, c) {
  // detach the event handler
  $someElement.off('click', someFunction);

  /* useful stuff here */

  // reattach the event handler
  $someElement.on('click', someFunction(a, b, c));
}

where I have cached the jQuery element.

Alternatively, you could create a variable outside of the callback's scope, checking and setting it's value inside the callback:

$(someSelector)).bind('click', someFunction(a,b,c));

var isWaiting = false;
function somefunction(a,b,c) {
  if (!isWaiting) {
    isWaiting = true;

    /* useful stuff here */

    isWaiting = false;
  }
}

I would recommend the .on/.off approach as it deals more directly with the jQuery event binding process.

Community
  • 1
  • 1
Alex
  • 9,313
  • 1
  • 39
  • 44