最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - new Event('build') vs new CustomEvent('build') - Stack Overflow

programmeradmin3浏览0评论

On this MDN page Creating and Triggering Events it shows an example of creating event with Event or CustomEvent. It explains that CustomEvent allows for custom details, but other than that, it doesn't say much.

So, what is the difference? If I'm creating a generic scroll event, should I use CustomEvent? Or is it only for events not exist in javascript?

Also, I noticed that MouseEvent is also a child of Event, so if I'm creating a click event, I can just use new MouseEvent('click')?

Thanks

On this MDN page Creating and Triggering Events it shows an example of creating event with Event or CustomEvent. It explains that CustomEvent allows for custom details, but other than that, it doesn't say much.

So, what is the difference? If I'm creating a generic scroll event, should I use CustomEvent? Or is it only for events not exist in javascript?

Also, I noticed that MouseEvent is also a child of Event, so if I'm creating a click event, I can just use new MouseEvent('click')?

Thanks

Share Improve this question edited Apr 24, 2015 at 20:21 Evan Davis 36.7k7 gold badges52 silver badges58 bronze badges asked Apr 24, 2015 at 20:18 BigNameBigName 1,1072 gold badges17 silver badges29 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

From that guide:

To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.

You can use Event() for anything. If you want to attach custom data, you use CustomEvent('eventName', {data}).

And yes, for mouse-events, you should use MouseEvent.

In all modern browsers:

const ev = new Event('foo')
ev.whatever = 123
console.log('event:', ev.whatever)

We can simply use Event directly like that, or even extend from Event to make a custom event:

class MyEvent extends Event {
  whatever = 123

  constructor() {
    super('my-event', {bubbles: true, posed: true, cancelable: false})
  }
}

someElement.dispatchEvent(new MyEvent()) // simple and done.

Nowadays there is absolutely no need for CustomEvent to even exist, and we can just use Event.


In the past, it may not have been possible to extend from Event using pre-ES6 function classes, but this limitation has long since been overe in all browsers, and classes can extend from native classes.

发布评论

评论列表(0)

  1. 暂无评论