【问题标题】:Replace customElements.define with custom logic用自定义逻辑替换 customElements.define
【发布时间】:2020-10-30 11:10:41
【问题描述】:

是否可以修改customElements.define 并改用自定义函数?

这是我迄今为止尝试过的,但显然这不起作用,因为window.customElements 是只读的。

const future = ["hello-world"];

let customElementsRegistry = window.customElements;
const registry = {};
registry.define = function(name, constructor, options) {
  if (future.includes(name)) {    
    customElementsRegistry.define(name, constructor, options);
  }  
}
window.customElements = registry;

window.customElements.define("hello-world", HelloWorld);

这是可能的还是我唯一的选择来创建我自己的registry 并使用那个?

【问题讨论】:

    标签: javascript web-component custom-element


    【解决方案1】:

    该属性仍然是可配置的,因此您可以重新定义它。虽然这对于生产应用程序来说看起来不是一个好主意。

    const future = ["hello-world"];
    
    let customElementsRegistry = window.customElements;
    const registry = {};
    registry.define = function(name, constructor, options) {
      console.log('hijacked')
      if (future.includes(name)) {
        customElementsRegistry.define(name, constructor, options);
      }
    }
    Object.defineProperty(window, "customElements", {
      get() {
        return registry
      }
    })
    
    window.customElements.define("hello-world", class HelloWorld extends HTMLElement {
      constructor() {
        super()
        this.innerHTML = "Hello World"
      }
    });
    <hello-world>Test</hello-world>

    【讨论】:

    • 好的,很酷。这背后的想法是能够门禁目前不应该公开的东西。所以这结合:not(:defined) { display:none } 至少对我来说是一种在我的应用程序中隐藏小组件的优雅方式。你能详细说明为什么这是一个坏主意吗?除了一般来说劫持东西可能是个坏主意:)
    • 只是关于猴子补丁的所有一般内容。就像如果您更改第三方(或其他开发人员)代码可能会中断的行为。例如,还有许多其他方法可以实现以准确匹配接口。
    • 我同意。是否可以只替换 define 函数并保持所有其他函数不变?
    • 我猜是这样,这应该可以解决问题Object.defineProperty(window.customElements, "define", { enumerable: false, value: function define() { /* custom logic here */}} )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2011-02-19
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多