我的问题真的是“the lapsed listener problem 可以在 javascript 中预防吗?”但显然“问题”这个词引起了问题。
维基百科页面说失效的监听器问题可以通过持有 weak references 的主题来解决。给观察员。我以前用 Java 实现过它并且工作得很好,我想我会用 Javascript 实现它,但现在我不知道如何实现。 javascript甚至有弱引用吗?我看到 WeakSet
和 WeakMap
的名称中包含“Weak”,但据我所知,它们似乎对此没有帮助。
这是一个 jsfiddle显示问题的典型案例。
html:
<div id="theCurrentValueDiv">current value: false</div>
<button id="thePlusButton">+</button>
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);
});
在这个 fiddle 中,可观察状态是一个 bool 值,您可以添加和删除查看和控制它的复选框,所有这些都由其上的监听器保持同步。 问题是,当您删除其中一个 Controller 时,它的监听器不会消失:监听器不断被调用并更新 Controller 复选框并阻止该复选框被 GC,即使该复选框不再在 DOM 中并且是否则GCable。您可以在 javascript 控制台中看到这种情况,因为监听器回调会向控制台打印一条消息。
我想要的是当我从 DOM 中删除节点时, Controller DOM 节点及其关联的值监听器变为 GCable。从概念上讲,DOM 节点应该拥有监听器,而可观察对象应该持有对监听器的弱引用。有没有一种干净的方法可以做到这一点?
我知道我可以通过使 x
按钮显式删除监听器以及 DOM 子树来解决我的 fiddle 中的问题,但是如果app 稍后删除了包含我的 Controller 节点的 DOM 的一部分,例如通过执行 document.body.innerHTML = ''
。我想设置一些东西,以便在发生这种情况时,我创建的所有 DOM 节点和监听器都被释放并成为 GCable。有办法吗?
最佳答案
Custom_elements为 lapsed listener problem 提供解决方案.它们在 Chrome 和 Safari 中受支持,并且(自 2018 年 8 月起)很快将在 Firefox 和 Edge 中受支持。
我做了一个jsfiddle使用 HTML:
<div id="theCurrentValue">current value: false</div>
<button id="thePlusButton">+</button>
并稍加修改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;
我们现在可以定义自定义 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();
}
});
这里的关键点是disconnectedCallback()
保证在 <my-control>
时被调用无论出于何种原因从 DOM 中删除。我们用它来移除监听器。
您现在可以添加第一个 <my-control>
与:
const plusButton = document.getElementById("thePlusButton");
plusButton.addEventListener("click", () => {
const myControl = document.createElement("my-control");
document.body.insertBefore(myControl, plusButton);
});
(我在观看 this video 时想到了这个答案,演讲者解释了自定义元素可能有用的其他原因。)
关于javascript - 在 javascript 中可以防止失效的监听器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43758217/