简体   繁体   中英

How to override/proxy disconnectedCallback in Custom Web Components

I am trying to proxy the disconnectedCallback of any instance of a custom element. Here is a cut down version of trying to do that:

const template = document.createElement("template");
template.innerHTML = `<button id="button">Click ME</button>`;

customElements.define("custom-test", class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: "open" });
      this.shadowRoot.appendChild(template.content.cloneNode(true));
    }

    disconnectedCallback() {
      console.log("Disconnected Callback")
    }
  },
);

let test = document.createElement('custom-test')
test = (function () {
  const fn = test.disconnectedCallback;
  test.disconnectedCallback = function () {
    console.log("proxy function")
    fn.apply(test)
  }
  return test;
})()

document.body.appendChild(test)

const div = document.createElement('div');
div.appendChild(test);
// Only outputs "Disconnected Callback"

I would expect to see the following output in the console:

proxy function
Disconnected Callback

But I can only see the second line, ignoring the proxy function. What do I need to do to override the function?

I tried using the new Proxy method but I can't do that because the Proxy element this creates cannot be used in the appendChild method.

If I explicitly call disconnectedCallback on the element

test.disconnectedCallback()
// Outputs the proxy function too

it does call the proxy like in the last line it does call the proxy.

After looking into this more I don't think it is possible. The issue is the functions defined on the class such as disconnectedCallback are defined on the object's prototype and can't be overriden in the same way (and if there is a way you probably shouldn't anyway).

I am instead going to look at creating a mixin for the class which handles the behaviour of conditionally calling the disconnect/connect functionality of the web component.

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