创建扩展SVGCircleElement的自定义元素时遇到错误

问题描述 投票:0回答:1

我有以下Node类,我将使用这些类来创建自定义元素node-element

class Node extends SVGCircleElement{
    static get observedAttributes() {
        return ["coordinates"];
      }
    constructor()
    {
        super();
        this.attributeMap = {coordinates:(coordinates)=>this.updateCoordinates(coordinates)}
    }
    connectedCallback(){
        this.initNode();
    }
    updateCoordinates(coordinates)
    {
        this.setAttribute("cx",`${coordinates.x}`);
        this.setAttribute("cy",`${coordinates.y}`);
        this.setAttribute("r",50);
    }
    initNode()
    {
        this.className="node";
    }
    attributeChangedCallback(name,oldValue,newValue)
    {
        if(oldValue!==newValue)
        {
            this.attributeMap[name](JSON.parse(newValue))
        }
    }
}

我使用以下元素注册此元素:-

customElements.define('node-element',Node);

我正在如下创建此元素:-

let newNode = document.createElement("node-element");

这是我收到以下错误的地方:-

Uncaught TypeError: Illegal constructor
    at new Node (index.js:9)
    at SVGSVGElement.drawNode (index.js:43)

第43行对应于createElement代码。

javascript svg web-component custom-element
1个回答
0
投票

想证明自己的爱是错误的,仅仅花了两个月的时间在SVG项目上

AFAIK,您不能扩展SVG元素

您只能在HTML命名空间http://www.w3.org/1999/xhtml中创建自定义元素

SVG元素在SVG命名空间http://www.w3.org/2000/svg

来自文档:https://html.spec.whatwg.org/multipage/custom-elements.html#element-definition

如果扩展的元素接口且HTML名称空间是HTMLUnknownElement,然后抛出“ NotSupportedError” DOMException。

如果命名空间不是HTML命名空间,则返回null

关于允许SVG名称空间的W3C开放讨论在这里:https://github.com/w3c/webcomponents/issues/634

注意:Apple / Safari拒绝实现自定义内置元素因此,如果您将文件传送到Safari,则只能扩展HTMLElement(或使用polyfill)

© www.soinside.com 2019 - 2024. All rights reserved.