事件与CustomEvent [英] Event vs CustomEvent

查看:161
本文介绍了事件与CustomEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 CustomEvent 的目的是什么,因为它可以很容易地被旧的 Event 模仿

I was wondering, what is the purpose of CustomEvent, because it can be easily emulated by good old Event.

那么,之间有什么区别:

So, what is the difference between:

var e = new Event("reload");
e.detail = {
    username: "name"
};
element.dispatchEvent(e);

var e = new CustomEvent("reload", {
    detail: {
        username: "name"
    }
});
inner.dispatchEvent(e);

为什么 CustomEvent 为什么存在?将自定义数据附加到普通的Event对象上?

Why does CustomEvent exist if it is easy to attach custom data to ordinary Event object?

推荐答案

不一样。您不能设置真实CustomEvent的详细信息

It's not the same. You can't set the detail of a real CustomEvent:

var event = new CustomEvent('myevent', {detail:123});
event.detail = 456; // Ignored in sloppy mode, throws in strict mode
console.log(event.detail); // 123

var event = new Event('myevent');
event.detail = 123; // It's not readonly
event.detail = 456;
console.log(event.detail); // 456

是的,您可以使用 Object.defineProperty 。但是我想关键是 CustomEvent 的参数应该设置事件的一些内部数据。现在,它只考虑 detail 的详细信息,该信息未在内部使用。但是将来的规范可能会添加一些新内容,然后您可能无法使用属性来设置内部数据。

Yes, you could use Object.defineProperty. But I guess the point is that the argument of CustomEvent was supposed to set some internal data of the event. Now it only considers detail, which is not used internally. But a future spec could add something new, and then you may not be able to set that internal data by using properties.

CustomEvent也继承自 CustomElement.prototype 。这样只会添加 detail 和不推荐使用的 initCustomEvent 。但是您可以在其中添加自己的方法或属性,而其他事件不会继承这些方法或属性。但是我不建议这样做,您不应该修改您不拥有的对象。

A CustomEvent also inherits from CustomElement.prototype. That only adds detail and the deprecated initCustomEvent. But you can add your own methods or properties in there, which won't be inherited by other events. But I don't recommend this, you shouldn't modify objects you don't own.

因此基本上可以使用 CustomEvent 以便对事件进行不同于其他事件的分类。从旧版本中查看此图形规范

So basically you can use CustomEvent in order to classify the event differently than other events. See this graphic from an old spec

这篇关于事件与CustomEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆