暂时禁止 jQuery 事件处理 [英] Suppress jQuery event handling temporarily

查看:9
本文介绍了暂时禁止 jQuery 事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种优雅的方法可以暂时抑制 jQuery 事件?我使用这样的代码:

Is there an elegant way to temporarily suppress jQuery events? I use code like this:

$(element).unbind(event, function1).unbind(event, function2);
// code for which the event is suppressed
$(element).bind(event, function1).bind(event, function2);

但我觉得它有点笨拙,而且对于许多事件的扩展性都不是很好.为什么我要暂时抑制事件?我使用 BlockUI 插件在 Ajax 访问期间阻止 UI.这是通过 BlockUI 建议的 $().ajaxStart($.blockUI).ajaxStop($.unblockUI) 完成的.

but I find it a bit clumsy and not very scalable to many events. Why do I want to suppress events temporarily? I use BlockUI plugin to block UI during Ajax access. This is done with: $().ajaxStart($.blockUI).ajaxStop($.unblockUI) as proposed by BlockUI.

但是,一个 Ajax 访问是特殊的,所以我需要一个不同的消息.ajaxStart 和 ajaxStop 事件会干扰消息代码(没有显示):

However, one Ajax access is special, so I need a different message. The ajaxStart and ajaxStop events interfere with the message code (nothing is shown):

function message(text, callback) {
  if (text == undefined) {
     $.unblockUI();
     return;
  }

  // $().unbind('ajaxStop', $.unblockUI).unbind('ajaxStart', $.blockUI);
  $("#message_text").html(text);
  $.blockUI({message: $("#message")});
  $("#message_ok").click(function() { 
    // $().bind('ajaxStop', $.unblockUI).bind('ajaxStart', $.blockUI);
    $.unblockUI();
    if (callback != undefined) callback();
  });
}

只有当我取消注释 unbind() 和 bind() 行时,它才能工作.

Only if I uncomment the unbind() and the bind() lines, it is working.

推荐答案

我意识到这个问题很老了,但是我在寻找同一个问题的答案时发现了它,最终找到了一个在简单应用程序中运行良好的不同解决方案的事件处理程序.

I realize this question is old, but I found it while seeking an answer to the same question, and ended up finding a different solution that works well in simple applications of event handlers.

$(element).click(function(e) {
  e.preventDefault();

  // Check for fired class
  if ($(this).hasClass('fired') == false) {
     // Add fired class to all instances of element
     $(element).addClass('fired');

     // Do the rest of the function...

     // Remove fired class to 'reactivate' events
     $(element).removeClass('fired');   
  }
}

在触发事件的代码时,只需将一个类添加到您的元素"中,您就可以防止由于另一个点击事件而执行进一步的代码.因此,虽然您实际上并没有阻止任何其他点击事件,但您正在阻止生成的代码运行.简单、粗暴,忽略了大肆宣传的 bind 和 unbind 的使用,但是有效.

Simply adding a class to your 'element's while the code from the event is firing allows you to prevent further code from being executed as the result of another click event. So while you're not actually preventing any other click events, you're preventing the resulting code from running. Simple, crude, ignores the heavily preached use of bind and unbind, but works.

这篇关于暂时禁止 jQuery 事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆