簡體   English   中英

使用Java腳本刪除事件監聽器

[英]Remove event listeners using Javascript

我想使用Java腳本刪除事件偵聽器,但似乎無法正常工作...

我的代碼不起作用:

function add () {
  var container = this.container;
  var span = document.createElement('span');
  span.classList.add('tooltip');
  span.innerHTML = this.msg;
  container.appendChild(span);
  this.tooltip = span;
  this.inputString.input.addEventListener('mouseenter', show.bind(this));
  this.inputString.input.addEventListener('mouseout', hide.bind(this));
}

function remove() {
  if (this.container.getElementsByClassName('tooltip').length) {
    this.inputString.input.removeEventListener('mouseenter', show);
    this.inputString.input.removeEventListener('mouseout', hide);
    this.container.removeChild(this.tooltip);
    this.msg = null;
    this.inputString = null;
    this.container = null;
    this.tooltip = null;
  }
}

function show () {
  var container = this.container,
      mainElmt = this.inputString.mainElmt,
      tooltip = this.tooltip;
  if ((container.offsetWidth - (mainElmt.offsetLeft + mainElmt.offsetWidth)) < ($(tooltip).outerWidth() + 5)) {
    tooltip.style.left = parseInt(mainElmt.style.left || getComputedStyle(this.inputString.el).left, 10) - ($(tooltip).outerWidth() + 5) + 'px';
    tooltip.classList.add('is-on-right');
  } else {
    tooltip.style.left = parseInt(mainElmt.style.left || getComputedStyle(this.inputString.el).left, 10) + parseInt(mainElmt.style.width || this.inputString.el.style.width, 10) + 5 + 'px';
    tooltip.classList.add('is-on-left');
  }
  tooltip.style.top = parseInt(mainElmt.style.top || getComputedStyle(this.inputString.el).top, 10) - 15 + (parseInt(mainElmt.style.height || this.inputString.el.style.height, 10) / 2) + 'px';
  tooltip.style.display = 'block';
}

.bind()創建一個副本,因此當您使用.removeEventListener您實際上是在傳遞另一個引用。

您有2個方法:

1)您可以存儲綁定函數:

this.show = show.bind(this);

然后使用它:

.addEventListener('...', this.show);
.removeEventListener('...', this.show);

2)將以下功能添加this原型:

// Assuming that `this` is an instance of function MyClass() {}
MyClass.prototype.show = function show() {...}

當您調用show.bind(this)這將有效地創建一個新函數。 所以當你寫:

this.inputString.input.addEventListener('mouseenter', show.bind(this));

這增加了一個功能(我們稱它為功能A)

當你寫的時候

this.inputString.input.removeEventListener('mouseenter', show.bind(this));

這將刪除其他功能(功能B)。

您需要存儲一個引用,並添加和刪除相同的功能,以使其正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM