簡體   English   中英

可以通過取消其回調函數來刪除EventListener嗎?

[英]Can an EventListener be removed by nullifying its callback function?

我想知道是否可以通過取消其回調函數來刪除事件監聽器?

簡化示例:

var somefunction = function() {
  // some code
}
window.addEventListener(eventType, somefunction, false); 

現在,將設置somefunction = null; 刪除上面的EventListener,還是將其簡單地變成僵屍EventListener?

實際的代碼在Firefox(覆蓋類型)插件中使用,我正在考慮(顯而易見的)在unload事件上(自動)刪除EventListener的替代方法,除了顯而易見的方法:

window.removeEventListener(eventType, somefunction, false); 

更新:請注意,這是Firefox插件代碼的一部分。 在這種情況下,eventType是'popupshowing' ,不能將其無效,因為它將破壞瀏覽器的功能。

預先感謝您的幫助期待(替代)建議

removeEventListener是必經之路。

同樣,您實際上並不通過將某些變量設置為null使函數null 該變量僅分配了一個引用(對非POD對象,如函數)。 為了說明這一點,請考慮以下內容:

var a = function() { alert("called"); };
setTimeout(a, 1000); // Will still alert!

var b = a;

a = null; // What you called `nullify`....
console.log(this.a, "a" in this); // null, true
delete this.a; // Actually remove the property from the global scope.
// `a` is really dead at this point!

b(); // will still alert, too.

如果要避免一些removeEventListener調用,我將使用一些輔助函數:

let { addEventListenerUnload, removeEventListenerUnload } = (function() {
  let tracked = [];
  addEventListener("unload", function removeTracked() {
    removeEventListener("unload", removeTracked);
    for (let t of tracked) {
      try {
        removeEventListener(t.type, t.fn, t.capture);
      }
      catch (ex) {}
    }
    tracked.length = 0;
  });
  return {
    addEventListenerUnload: function(type, fn, capture) {
      addEventListener(type, fn, capture);
      tracked.push({type: type, fn: fn, capture: capture});
    },
    removeEventListenerUnload: function(type, fn, capture) {
      tracked = tracked.filter(e => e.type != type || e.fn != fn || e.capture != capture);
      removeEventListener(type, fn, capture);
    }
  };
})();

(包括Firefox支持的ECMA-6內容,但您可以輕松轉換。此外,可能根本不需要removeEventListenerUnload ,因此您可以省略它。此外,在覆蓋腳本中使用此名稱時,請確保為其指定唯一的名稱避免與其他代碼沖突)。

我不認為將回調函數設置為null會刪除eventlistener,您仍然會附加eventlistener,可以使用removeEventListener或將eventType設置為null,例如:

window.eventType = null;

暫無
暫無

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

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