Skip to main content

EventProxy

EventProxy can host events for web elements, EventProxy is essentially an encapsulation of SyncEvents

所以 EventProxy 具有几乎所有 SyncEvent 的方法,除了emit

Initialization

import { EventProxy } from "ocev"
// Make sure element can 'addEventListener' and 'removeEventListener', theoretically all web elements can.

EventProxy.new(element) // or new EventProxy(element)

Usage

  const divRef = useRef<HTMLDivElement>(null)

useEffect(() => {
// Complete Type Tips
return EventProxy.new(divRef.current!)
.on("click", (ev) => {})
.on("mouseenter", (ev) => {})
.on("mouseleave", (ev) => {})
}, [])

return <div ref={divRef}></div>

Listen to all events

Two ways to monitor

EventProxy.new(element, { proxyAllEvent: true }).any((event) => {
console.log(event, "trigger")
})

or

EventProxy.new(element).proxyAllEvent().any((event) => {
console.log(event, "trigger")
})

In react you can write something like this

  const divRef = useRef<HTMLDivElement>(null)

useEffect(() => {
// 完整的类型提示
return EventProxy.new(divRef.current!)
.on("click", (ev) => {})
.on("mouseenter", (ev) => {})
.on("mouseleave", (ev) => {})
}, [])

return <div ref={divRef}></div>

Optional Configuration

EventProxy.new(divRef.current!, {
proxyAllEvent: true,
addEventListenerOptions: {
passive: true,
}, // consistent with parameters of 'addEventListener'
})

Get the original element

const div = document.createElement('div')
EventProxy.new(div).element === div

Destroy

EventProxy.new(element).destroy() // Clean up all event registrations