【发布时间】:2020-08-23 17:19:46
【问题描述】:
我有以下 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 代码。
【问题讨论】:
-
你能告诉我如何将它与“node-element”一起使用吗?
-
您是否成功扩展(其他)SVG 元素?
-
@enxaneta 我尝试了 document.createElementNS("w3.org/2000/svg","node-element")。这没有给出错误,但没有调用任何构造函数或生命周期方法。我使用控制台日志对其进行了验证。
-
@Danny'365CSI'Engelman 我的要求是只使用圆形元素,所以我只扩展了它的类。
标签: javascript svg web-component custom-element