简体   繁体   中英

Cannot pass Proxy around html element to appendChild

I wrote a thin wrapper which gets passed a node created by document.createElement and adds a few methods. This wrapper is realized with a Proxy. All I do is catching some getters.

  return new Proxy(node, {
    get (target, prop) {
      if (prop === 'node') return target

      if (wFuncs[prop]) {
        return Reflect.get(target, wFuncs[prop]).bind(target)
      }

      return Reflect.get(target, prop)
    }
  })

I would have expected to be able to pass such a proxy to appendChild since it is still an instance of Node and has all the properties and methods from an html element. However, appendChild comlpains that the passed element is not a Node:

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

Any ideas on how to solve this?

We can redeclare global appendChild behavior. Like this:

  1. Create internal __element property, that returns a real node
return new Proxy(node, {
        get (target, prop) {
          if (prop === 'node') return target
          if (prop === '__element') return node
    
          if (wFuncs[prop]) {
            return Reflect.get(target, wFuncs[prop]).bind(target)
          }
    
          return Reflect.get(target, prop)
        }
      });
  1. Change global appendChild
Node.prototype.appendChild = function (el) {
  if (el["__element"]) {
    return _appendChild.call(this, el["__element"]);
  } else {
    return _appendChild.call(this, el);
  }
};

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