为什么在设置订阅后没有发生新的mousedown事件时触发我的mousedown订阅



在我的Angular应用程序中,我有一个函数,它由单击我按钮上的(mousedown)输出事件调用。函数包含订阅未来mousedown事件的代码。

然而,奇怪的是,订阅甚至在发生任何其他mousedown事件之前就启动了。

我创建了一个Stacklitz来演示(+源代码(,但这里是粘贴在这里的代码:

@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
output = '';
performActionOnClick() {
console.log("Action [1] Performed!");
this.output += "nAction [1] Performed!";
fromEvent<MouseEvent>(document, "mousedown").subscribe(
this.performActionOnTrigger.bind(this)
);
}
performActionOnTrigger() {.                      <------ this function gets called despite
console.log("Action [2] Performed!");                  only one mouse click !
this.output += "nAction [2] Performed!";
}
}

为什么只需单击一次鼠标就可以调用此函数

正如Teedeez所评论的,发生这种情况的原因是"冒泡"或事件传播。

鼠标事件首先在最里面的元素,即按钮上触发,然后在父元素和它的父元素等上触发,一直到窗口。

点击此处阅读更多:

https://www.sitepoint.com/event-bubbling-javascript/

您可能需要重新考虑您的事件侦听器来解释这一点,或者您可以在事件中指定它不正确。

最新更新