jquery - 快乐的点击器 - 寻找绑定事件的回调

时间:2012-04-09 07:19:56

标签: javascript jquery

我将一些稍微复杂的功能绑定到点击事件

$(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");
            })
        })

    }
}

问题是一系列快速点击会导致fadeOut / fadeIn行为不一致。我假设在当前的fadeIn完成之前处理了新的点击事件。

我认为我正在寻找一些回调机制,以确保在当前点击完成后处理新点击。我可以为fadeIn添加一个回调,但是我没有看到我的逻辑会帮助我...

只要处理了一个点击(后来重新绑定它们),我也会读到关于取消绑定组件的内容,但是再次 - 我不确定我会把它放在哪个逻辑上。

感谢您的建议:)

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery的.on.off方法:

$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));
}

我有cached the jQuery element

或者,您可以在回调范围之外创建一个变量,在回调中检查并设置它的值:

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

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

    /* useful stuff here */

    isWaiting = false;
  }
}

我建议采用.on / .off方法,因为它更直接地处理jQuery事件绑定过程。