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

时间:2019-04-10 15:20:46

标签: javascript jquery

我试图理解为什么需要删除事件处理程序。我是一名初学者开发人员,我在各处搜索了答案,但找不到原因。 我遇到了下面的代码,并且看到绑定的事件处理程序被立即删除。这是一个好习惯吗?

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

1 个答案:

答案 0 :(得分:0)

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.

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).

Is it a good practice?

Non working code is not a good practice, no. Removing an event listener sometimes makes sense (e.g. 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).