为什么 attributeChangedCallback 被调用了两次?

Why is attributeChangedCallback called twice?

我正在构建一个简单的自定义元素,使用 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 查找和调试函数。

由于 custom-elements.js polyfill 是一个 alpha 版本并且还不稳定,你应该使用 polyfill from WebReflection: