【发布时间】:2017-01-18 11:27:47
【问题描述】:
我正在使用custom elements polyfill 构建一个简单的自定义元素。我已经注册了一个被“监视”的属性(使用observedAttributes()),当我改变这个属性的值时,函数attributeChangedCallback被调用了两次。
这是 HTML 代码:
<my-component id="compo" foo="bar"></my-component>
<button id="myBtn">Change attribute value</button>
这是我的组件定义:
class MyComponent extends HTMLElement {
constructor() {
super();
}
static get observedAttributes() {
return ['foo'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log('[my component] attribute', attrName, 'changed from', oldVal, 'to', newVal);
}
}
window.customElements.define('my-component', MyComponent);
// Change value of the component attribute
$('#myBtn').click(() => $('#compo').attr('foo', 'baz'));
在该页面上,当我单击按钮时,console.log 中有以下日志:
[我的组件] foo 属性从 bar 更改为 baz
[我的组件] foo 属性从 bar 更改为 baz
为什么attributeChangedCallback 被调用了两次?如何避免?
这个例子的 JSFiddle 在这里:https://jsfiddle.net/czo1355c/
谢谢。
【问题讨论】:
-
我得到了两个更改,但是在您的 JSFiddle 示例中从 null -> bar 然后 bar -> baz。
-
确实,但是 - 正如我在对@ikram-shah 答案的评论中所解释的那样,问题似乎出在 polyfill 上。 Chrome v54+ 原生实现
customElements,所以不使用polyfill,函数只调用一次。
标签: javascript html web-component custom-element