我正在构建一个简单的自定义元素,使用 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
中有以下日志:
[my component] attribute foo changed from bar to baz
[my component] attribute foo changed from bar to baz
为什么 attributeChangedCallback
被调用了两次?我该如何避免?
这个例子的 JSFiddle 在这里:https://jsfiddle.net/czo1355c/
谢谢。
最佳答案
我检查了你的 jsfiddle,它实际上并没有在按钮点击时被调用两次,而是在 <my-component id="compo" foo="bar"></my-component>
时第一次被调用。呈现,因为您正在设置 foo
的值;其次,当您点击按钮时。
您也可以在 jsfiddle 上调试它,使用开发者工具,然后按 Ctrl+Shift+F 找到并调试该函数。
关于javascript - 为什么 attributeChangedCallback 被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718254/