gpt4 book ai didi

javascript - 使用事件监听器调用服务

转载 作者:行者123 更新时间:2023-12-03 03:22:12 27 4
gpt4 key购买 nike

免责声明:标题并不十分准确。

我有一个带有公共(public)方法 openCamera 的服务,该方法调用全局对象中的库并将事件监听器附加到其 HTML 元素。当我从 HTML 元素事件调用此服务方法时,它工作正常,但当我通过附加到窗口元素的事件调用它时,它工作正常。下面是一个例子:

class ImageService {
public static AttachEventOnce = false;
public openCamera() {
let camera = new JpegCamera('myContainer');
// captureBtn and videoBox are HTML elements generated from the library once instantiated
camera.captureBtn.addEventListener('click', () => this.openCamera()); // this works fine
camera.videoBox.addEventListener('resize', () => this.openCamera()); // doesn't enter here ie not calling it
if (!ImageService.AttachEventOnce) {
var that = this;
window.addEventListener('resize', () => that.openCamera()); // the buttons stop working
ImageService.AttachEventOnce = true;
}
};
}

逻辑有所简化,但或多或​​少相同。我只是想在调整窗口大小时一次又一次地调用服务方法。我不关心在哪里附加监听器(从库或窗口生成的 HTML 元素)。

我的看法:窗口似乎也保留了旧的对象引用以及其他按钮的监听器,我认为这是导致问题的原因。

最佳答案

The window seem to retain the older object reference too as well as other listerers for other buttons which I think is causing the issue.

正确 - 不是因为它位于 window 上,而是因为您使用了箭头函数并且仅在 openCamera 的第一个实例上 Hook 事件一次 被调用。因此,该实例是否被其他所有实例丢弃并不重要,它是唯一实例将接收该resize事件。 (也没有理由使用 var that = this; 事物,然后在函数内使用 that;箭头函数像它们一样关闭 this变量,因此它的作用与在函数中使用 this 的作用完全一样。)

目前尚不清楚为什么要这样做,而不是像其他事件一样以特定于实例的方式 Hook 事件。如果您仅删除一次 Hook 的逻辑,您将获得每个实例的行为。

另外:每次事件发生时都附加事件处理程序是很奇怪的。你很快就会把它们堆起来。第一次(比方说)您收到 click 时,您将添加第二个 click 处理程序;下次您收到点击时,您将收到其中两个(每个处理程序一个),并添加两个更多处理程序;依此类推,每次都加倍。这对于点击来说已经够糟糕的了,但是对于resize来说更是灾难性的,因为在调整窗口大小时会触发很多resize事件。 p>

关于javascript - 使用事件监听器调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46520902/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com