简体   繁体   中英

How are *custom* events in JavaScript actually implemented?

As far as I understand, events are not part of EcmaScript language, but of the DOM specification and DOM implementations in the various engines. From reading about the DOM, I got the impression that the events are build-in to the engines and you can't have custom ones. On the other hand, frameworks like jQuery give functions that define custom events. Similarly you can have custom events in server-side JavaScript frameworks like Node.js.

I tried to do some research about that and the only conclusion I could come up with is that the "custom" events are actually abstractions over true (built-in) events, that the frameworks handle in hidden parts of the DOM, that are created for that specific purpose.

Is that correct? If not, how are user-defined events actually implemented in JavaScript?

The DOM events specification ( v2 , v3 ) provides a means of creating and dispatching events, via methods such as createEvent and dispatchEvent . It's a DOM thing, not a JavaScript thing. (JavaScript's various features around functions — their being closures , being first-class objects, etc. — make it really easy to implement events via an observer-style pattern, but that's a different topic.)

This article deeply discusses the problem and provides a pretty solid solution to building "abstractions" around existing dom events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM