gpt4 book ai didi

javascript - 如何扩展自定义元素 ("vanilla"网络组件,无聚合物)

转载 作者:行者123 更新时间:2023-11-27 23:39:40 24 4
gpt4 key购买 nike

我有一个自定义元素,叫做 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.

改用继承?好的,具体如何? 有例子吗?

注意:我没有使用 Polymer。只是 Chrome 中的普通网络组件,没有 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"网络组件,无聚合物),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32213051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com