为什么自设置订阅以来没有发生新的mousedown事件,为什么触发了mousedown订阅?

问题描述 投票:0回答:1

在我的Angular应用程序中,我有一个函数,该函数由Click Me按钮上的(mousedown)输出事件调用。该函数包含预订future mousedown事件的代码。

但是,奇怪的是,即使发生[[before任何其他mousedown事件,订阅仍会触发。

我创建了一个Stackblitz to demonstrate(+ source code),但这是粘贴在此处的代码:

@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!"; } }

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

angular typescript rxjs mousedown
1个回答
1
投票
如Teedeez所说,之所以发生,是因为“冒泡”或事件的传播。

鼠标事件首先在最里面的元素即您的按钮上触发,但随后在父对象及其父对象上一直触发,一直到窗口。

在这里阅读更多:

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

您可能必须重新考虑事件监听器以解决此问题,或者您可以在事件中指定它不适当。

© www.soinside.com 2019 - 2024. All rights reserved.