$event 对象在 Angular 2 中究竟做了什么? [英] What exactly $event object do in Angular 2?
问题描述
我有点困惑 $event
在这里做了什么,这两个例子有什么区别
I am bit confused what exactly $event
doing here and what is the difference between this two examples
<button (click)="clicked($event)"></button>
@Component(...)
class MyComponent {
clicked(event) {
event.preventDefault();
}
}
和
<button (click)="clicked()">Click</button>
@Component(...)
class MyComponent {
clicked(event) {
}
}
推荐答案
$event
是事件本身.
事件绑定 (someevent)
允许绑定到 DOM 事件和 EventEmitter
事件.语法完全一样.
The event binding (someevent)
allows to bind to DOM events and to EventEmitter
events. The syntax is exactly the same.
对于 DOM 事件,$event
是 MouseEvent
、KeyboardEvent
或您侦听的任何事件类型的事件值.
For DOM events $event
is the MouseEvent
, KeyboardEvent
, or the event value of the type of whatever event you listen to.
对于 EventEmitter
事件,发出的值可以作为 $event
For EventEmitter
events the emitted value is available as $event
假设这个例子 $event
指的是发出的 Ferrari
汽车实例:
Assuming this example $event
refers to the emitted Ferrari
car instance:
@Output() carChange:EventEmitter<Car> = new EventEmitter<Car>();
someMethod() {
this.carChange.emit(new Car({name: 'Ferrari'}));
}
如果您不像在 (click)="clicked()"
中那样使用 $event
,则不会传递事件值.
If you don't use $event
like in (click)="clicked()"
then the event value is not passed.
实际上据我所知仍然在某些浏览器中传递但不是全部(不记得是哪些)
Actually as far as I remember it is still passed in some browsers but not in all (don't remember which ones)
但是如果您使用 Angulars WebWorker 功能,那么如果您没有明确列出它,您的方法可能不会获得触发或发出的事件.
But if you use Angulars WebWorker feature, then your method might not get the fired or emitted event if you don't explicitely list it.
这篇关于$event 对象在 Angular 2 中究竟做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!