为什么 attributeChangedCallback 被调用两次?

Rom*_*las 5 html javascript web-component custom-element

我正在使用自定义元素 polyfill构建一个简单的自定义元素。我已经注册了一个要“监视”的属性(使用observedAttributes()),当我更改此属性的值时,该函数会attributeChangedCallback被调用两次。

这是 HTML 代码:

<my-component id="compo" foo="bar"></my-component>

<button id="myBtn">Change attribute value</button>
Run Code Online (Sandbox Code Playgroud)

这是我的组件定义:

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'));
Run Code Online (Sandbox Code Playgroud)

在该页面上,当我单击按钮时,我在以下日志中有以下日志console.log

[我的组件] 属性 foo 从 bar 更改为 baz

[我的组件] 属性 foo 从 bar 更改为 baz

为什么要attributeChangedCallback调用两次?我怎样才能避免它?

这个例子的 JSFiddle 在这里:https ://jsfiddle.net/czo1355c/

谢谢。

Sup*_*arp 2

由于custom-elements.jspolyfill 是 alpha 版本并且还不稳定,因此您应该使用WebReflection 中的 polyfill来代替: