简体   繁体   English

为什么在此函数中删除了事件处理程序?

[英]Why are event handlers being removed in this function?

I'm trying to understand why event handlers need to be removed. 我试图理解为什么需要删除事件处理程序。 I'm a beginner developer, and I searched all over for the answer but couldn't find the reason. 我是一名初学者,我搜遍了所有答案,但找不到原因。 I came across the code below and I see that the event handler is removed as soon as it is bound. 我遇到了下面的代码,我看到事件处理程序一旦绑定就被删除。 Is it a good practice? 这是一个好习惯吗?

bindSubmitEvent: function() {
  var self = this;
  $('#submitBtn').on('click', function() {
    $(this).off('click', self.bindSubmitEvent);
    self.validateForm();

    if (self.options.valid_selection) {
      self.submitForm();
    } else {
      $('#submitRegistrationBtn').on('click', self.bindSubmitEvent);
      console.log("not valid");
    }
  });
}

The code you've shown does not work. 您显示的代码不起作用。 this inside the inner click handler is #submitButton , therefore trying to detach the self.bindSubmitEvent from it makes no sense, as that function was never attached to it. 内部单击处理程序内部的this#submitButton ,因此尝试从中分离self.bindSubmitEvent是没有意义的,因为该函数从未附加到它。

Also $('#submitRegistrationBtn').on('click', self.bindSubmitEvent) will cause more trouble, as two events will be attached at the next click, and the second one will be called with this (and therefore self being the #submitRegistrationBtn . That will probably cause the whole code to fail (silently). 此外$('#submitRegistrationBtn').on('click', self.bindSubmitEvent)会造成更多的麻烦,因为两个事件将在下次点击附着,而第二个将被用this (因此self作为#submitRegistrationBtn 。这可能会导致整个代码失败(无声)。

Is it a good practice? 这是一个好习惯吗?

Non working code is not a good practice, no. 非工作代码不是一个好习惯,不是。 Removing an event listener sometimes makes sense (eg if the form was submitted, you want the registration button to be disabled), in most cases however, it is way easier to just remove the button itself (as it serves no functionality without a listener attached). 删除事件监听器有时是有意义的(例如,如果表单已提交,您希望禁用注册按钮),但在大多数情况下,更容易删除按钮本身(因为它没有附加监听器就没有功能) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM