nep*_*dev 4 html javascript web-component custom-element
我正在探索Web组件自定义HTML元素,我遇到了向自定义元素添加自定义属性的问题:我在标记中设置的任何值都不会受到尊重.对于像这样的简单元素,它应该显示"flagtext"属性中提供的文本,它总是显示默认值.
<test-flag flagtext="my text"></test-flag>
Run Code Online (Sandbox Code Playgroud)
完整的JSBin示例在这里.
JSBin使用Polymer库(因为这是我唯一可以使用的).我一般使用webcomponents.js,结果相同.Chrome 49和Firefox 45都有相同的结果.控制台或调试器中没有显示错误.
我在网上找到的每个样本都有类似的代码,但我尝试了各种版本,它总是拒绝更新.我甚至将一些样本复制到JSBin中,但它们也没有用.
可能有什么不对?我知道这是实验性技术,但这种不一致的一致性仍然令人惊讶.这个标准被废弃了吗?(我看到最新的2016年4月W3C自定义元素草案已完全改变了它的方法.)
当我定义"attributeChangedCallback"函数时,它不会触发.我可以通过Javascript轻松修改属性,这不是问题.
但是为什么我不能在标记中指定属性,就像我应该的那样?
编辑 - 完整代码
请注意,您需要将这些文件放入单独的HTML导入文件中,并且需要"webcomponents-lite.js"库.
主HTML文件
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
test-flag
{
border: 1px solid blue;
}
</style>
</head>
<body>
<script src="lib/webcomponents-lite.min.js"></script>
<link rel="import" href="test-flag.html">
Here is the custom test-flag component:
<p>
<test-flag flagtext="my text"></test-flag>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
文件:test-flag.html
<template>
<style>
</style>
Content:
<div id="testflagID">
</div>
</template>
<script>
(function() {
var _currentScript = (document._currentScript || document.currentScript);
var importDoc = _currentScript.ownerDocument;
var customPrototype = Object.create(HTMLElement.prototype);
Object.defineProperty(customPrototype, 'flagtext', {value: '(default)', writable: true});
document.registerElement('test-flag', {prototype: customPrototype});
customPrototype.createdCallback = function()
{
var template = importDoc.querySelector('template');
var clone = document.importNode(template.content, true);
var idx = clone.querySelector("#testflagID");
idx.textContent = this.flagtext;
var root = this;
var createdElement = root.appendChild(clone);
};
})();
</script>
Run Code Online (Sandbox Code Playgroud)
有两个概念没有自动链接在一起.
在HTML代码中:
<test-flag flagtext="my text"></test-flag>
Run Code Online (Sandbox Code Playgroud)
... term flagtext 是HTML属性(不是属性).
在JavaScript代码中:
Object.defineProperty(customPrototype, 'flagtext', {value: '(default)', writable: true})
Run Code Online (Sandbox Code Playgroud)
... term flagtext 是JavaScript属性(不是属性).
对于标准元素,浏览器会自动将属性值绑定到属性值(反之亦然).对于自定义元素(使用标准属性).但是如果要添加自定义属性,则必须手动绑定它.
例如,在createdCallback()方法中,添加:
this.flagtext = this.getAttribute( 'flagtext' ) || '(default)'
Run Code Online (Sandbox Code Playgroud)
现场样本:
document.registerElement( 'test-flag' , {
prototype: Object.create( HTMLElement.prototype, {
flagtext: {
value: '(default)',
writable: true
},
createdCallback: {
value: function()
{
this.flagtext = this.getAttribute( 'flagtext' ) || this.flagtext
this.innerHTML = 'flagtext=' + this.flagtext
}
},
} )
} )Run Code Online (Sandbox Code Playgroud)
<test-flag flagtext='new content'>Hello</test-flag>Run Code Online (Sandbox Code Playgroud)
注意:attributeChangedCallback()只有在元素创建后更改属性时才会触发该方法(此处不是这种情况).