cloning javascript event object

前端 未结 4 1469
情歌与酒
情歌与酒 2020-11-28 13:07

Anybody know how to do a deep copy/cloning of a native javascript event object? I know I can create a new event object and set the appropriate properties manually to match

4条回答
  •  一生所求
    2020-11-28 13:17

    Option 1: Making a new event with modification

    You could make an Object.assign-alike using proxies and construct a new event without modifying the original event

    Example:

    function EventModifier (evt, obj) {
      const proxy = new Proxy(evt, {
        get: (target, prop) => obj[prop] || target[prop]
      })
      return new evt.constructor(evt.type, proxy)
    }
    
    onclick = evt => {
      evt = new EventModifier(evt, { altKey: true })
      // Dispatch the new event on something else
      console.log('clicked with alt key:', evt.altKey) // always true
    }

    This way you will use the same options as the original event that includes bubble, cancelable, key modifier, etc (doe it don't include any target as you are meant to dispatch the modified event on something else)

    Option 2: Define new properties

    Keeping the original event but override a key using Object.defineProperty you could use defineProperties if you want to add more than just one.

    onclick = evt => {
      Object.defineProperty(evt, 'target', { value: document.querySelector('script') })
      console.log('target:', evt.target)
    }

提交回复
热议问题