在我的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!";
}
}
?为什么只单击一次鼠标就会调用此函数
鼠标事件首先在最里面的元素即您的按钮上触发,但随后在父对象及其父对象上一直触发,一直到窗口。
在这里阅读更多:
https://www.sitepoint.com/event-bubbling-javascript/
您可能必须重新考虑事件监听器以解决此问题,或者您可以在事件中指定它不适当。