我有一个自定义元素,名为x-foo
。我想扩展它,并创建一个 x-bar
元素:
xBar = document.registerElement("x-bar", {
prototype: xBarProto,
extends: "x-foo"
});
但是这不起作用。不可能以这种方式扩展自定义元素。 Chrome 发出此错误:
Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'x-foo-extended'. The tag name specified in 'extends' is a custom element name. Use inheritance instead.
使用继承来代替?好吧,具体怎么样? 有什么例子吗?
注意:我没有使用聚合物。只是 Chrome 中的普通 Web 组件,没有 Polyfill。
最佳答案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Custom Element Inheritance</h1>
<nav>
<button onclick="addFoo()">Add Foo</button>
<button onclick="addBar()">Add Bar</button>
</nav>
<script>
//x-foo
var xFooProto = Object.create( HTMLDivElement.prototype )
xFooProto.createdCallback = function ()
{
this.innerHTML = "XFoo Custom Element"
}
var xFoo = document.registerElement( "x-foo", { prototype: xFooProto, extends: "div" } )
function addFoo()
{
console.log( "addFoo()" )
var xf = new xFoo
document.body.appendChild( xf )
}
//x-bar
xBarProto = Object.create( xFooProto )
xBarProto.attachedCallback = function ()
{
this.innerHTML = "XBar Custom Element inherits from " + this.innerHTML
}
var xBar = document.registerElement( "x-bar", { prototype: xBarProto, extends: "div" } )
function addBar()
{
console.log( "addBar()" )
var xb = new xBar
document.body.appendChild( xb )
}
</script>
</body>
</html>
您只能扩展标准 HTML 元素的受限子集,而不能扩展自定义元素。 你必须:
1) 获取 x-foo
原型(prototype)(我猜是 xFooProto
)。
2)继承它:
var xBarProto = Object.create( xFooProto )
3)用其特定的方法和属性对其进行增强。
4) 将其注册为原始 x-foo
基本元素的扩展:
document.registerElement( "x-bar", { prototype: xBarProto, extends: "div" } )
关于javascript - 如何扩展自定义元素("vanilla"Web组件,无Polymer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32213051/