在javascript中可以阻止已失效的侦听器吗?

Don*_*tch 5 javascript dom garbage-collection weak-references observer-pattern

我的问题是" javascript中是否可以阻止失效的侦听器问题?" 但显然"问题"这个词会导致问题.

维基百科页面说,失败的监听器问题可以通过持有对观察者的弱引用的主题来解决.我之前在Java中已经实现了它并且它运行良好,我认为我将在Javascript中实现它,但现在我不知道如何.javascript甚至有弱引用吗?我看到有WeakSetWeakMap具有在其名称中的"弱",但他们似乎并没有被这个有帮助,据我所看到的.

这是一个jsfiddle,显示了问题的典型案例.

html:

<div id="theCurrentValueDiv">current value: false</div>
<button id="thePlusButton">+</button>
Run Code Online (Sandbox Code Playgroud)

javascript:

'use strict';
console.log("starting");
let createListenableValue = function(initialValue) {
  let value = initialValue;
  let listeners = [];
  return {
    // Get the current value.
    get: function() {
      return value;
    },
    // Set the value to newValue, and call listener()
    // for each listener that has been added using addListener().
    set: function(newValue) {
      value = newValue;
      for (let listener of listeners) {
        listener();
      }
    },
    // Add a listener that set(newValue) will call with no args
    // after setting value to newValue.
    addListener: function(listener) {
      listeners.push(listener);
      console.log("and now there "+(listeners.length==1?"is":"are")+" "+listeners.length+" listener"+(listeners.length===1?"":"s"));
    },
  };
};  // createListenable

let theListenableValue = createListenableValue(false);

theListenableValue.addListener(function() {
  console.log("    label got value change to "+theListenableValue.get());
  document.getElementById("theCurrentValueDiv").innerHTML = "current value: "+theListenableValue.get();
});

let nextControllerId = 0;

let thePlusButton = document.getElementById("thePlusButton");
thePlusButton.addEventListener('click', function() {
  let thisControllerId = nextControllerId++;
  let anotherDiv = document.createElement('div');
  anotherDiv.innerHTML = '<button>x</button><input type="checkbox"> controller '+thisControllerId;
  let [xButton, valueCheckbox] = anotherDiv.children;
  valueCheckbox.checked = theListenableValue.get();
  valueCheckbox.addEventListener('change', function() {
    theListenableValue.set(valueCheckbox.checked);
  });

  theListenableValue.addListener(function() {
    console.log("    controller "+thisControllerId+" got value change to "+theListenableValue.get());
    valueCheckbox.checked = theListenableValue.get();
  });

  xButton.addEventListener('click', function() {
    anotherDiv.parentNode.removeChild(anotherDiv);
    // Oh no! Our listener on theListenableValue has now lapsed;
    // it will keep getting called and updating the checkbox that is no longer
    // in the DOM, and it will keep the checkbox object from ever being GCed.
  });

  document.body.insertBefore(anotherDiv, thePlusButton);
});
Run Code Online (Sandbox Code Playgroud)

在这个小提琴中,可观察状态是一个布尔值,您可以添加和删除查看和控制它的复选框,所有这些都由侦听器保持同步.问题是当你删除其中一个控制器时,它的监听器不会消失:监听器不断被调用并更新控制器复选框并阻止复选框被GCed,即使复选框不再在DOM中并且是否则GCable.您可以在javascript控制台中看到这种情况,因为侦听器回调会将消息输出到控制台.

我想要的是,当我从DOM中删除节点时,控制器DOM节点及其关联的值侦听器变为GCable.从概念上讲,DOM节点应该拥有侦听器,而observable应该拥有对侦听器的弱引用.有没有一个干净的方法来实现这一目标?

我知道我可以通过使x按钮显式删除侦听器以及DOM子树来解决问题,但是在应用程序中的某些其他代码随后删除包含我的控制器节点的DOM的部分情况下这无济于事,例如通过执行document.body.innerHTML = ''.我想要进行设置,以便在发生这种情况时,我创建的所有DOM节点和侦听器都会被释放并成为GCable.有办法吗?

Jam*_*mes 0

Custom_elements为失效侦听器问题提供了解决方案。它们在 Chrome 和 Safari 中受支持,并且(截至 2018 年 8 月)很快将在 Firefox 和 Edge 中得到支持。

我用 HTML做了一个jsfiddle :

<div id="theCurrentValue">current value: false</div>
<button id="thePlusButton">+</button>
Run Code Online (Sandbox Code Playgroud)

稍微修改一下listenableValue,现在可以删除侦听器:

"use strict";
function createListenableValue(initialValue) {
    let value = initialValue;
    const listeners = [];
    return {
        get() { // Get the current value.
            return value;
        },
        set(newValue) { // Set the value to newValue, and call all listeners.
            value = newValue;
            for (const listener of listeners) {
                listener();
            }
        },
        addListener(listener) { // Add a listener function to  call on set()
            listeners.push(listener);
            console.log("add: listener count now:  " + listeners.length);
            return () => { // Function to undo the addListener
                const index = listeners.indexOf(listener);
                if (index !== -1) {
                    listeners.splice(index, 1);
                }
                console.log("remove: listener count now:  " + listeners.length);
            };
        }
    };
};
const listenableValue = createListenableValue(false);
listenableValue.addListener(() => {
    console.log("label got value change to " + listenableValue.get());
    document.getElementById("theCurrentValue").innerHTML
        = "current value: " + listenableValue.get();
});
let nextControllerId = 0;
Run Code Online (Sandbox Code Playgroud)

我们现在可以定义一个自定义 HTML 元素<my-control>

customElements.define("my-control", class extends HTMLElement {
    constructor() {
        super();
    }
    connectedCallback() {
        const n = nextControllerId++;
        console.log("Custom element " + n + " added to page.");
        this.innerHTML =
            "<button>x</button><input type=\"checkbox\"> controller "
            + n;
        this.style.display = "block";
        const [xButton, valueCheckbox] = this.children;
        xButton.addEventListener("click", () => {
            this.parentNode.removeChild(this);
        });
        valueCheckbox.checked = listenableValue.get();
        valueCheckbox.addEventListener("change", () => {
            listenableValue.set(valueCheckbox.checked);
        });
        this._removeListener = listenableValue.addListener(() => {
            console.log("controller " + n + " got value change to "
                + listenableValue.get());
            valueCheckbox.checked = listenableValue.get();
        });
    }
    disconnectedCallback() {
        console.log("Custom element removed from page.");
        this._removeListener();
    }
});
Run Code Online (Sandbox Code Playgroud)

这里的关键点是,无论出于何种原因,当从 DOM 中删除disconnectedCallback()时,都保证会被调用。<my-control>我们用它来删除监听器。

您现在可以添加第一个<my-control>

const plusButton = document.getElementById("thePlusButton");
plusButton.addEventListener("click", () => {
    const myControl = document.createElement("my-control");
    document.body.insertBefore(myControl, plusButton);
});
Run Code Online (Sandbox Code Playgroud)

(我在观看此视频时想到了这个答案,其中演讲者解释了自定义元素可能有用的其他原因。)