Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - Event vs CustomEvent

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);

and

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

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

question from:https://stackoverflow.com/questions/40794580/event-vs-customevent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...