javascript - 为什么 attributeChangedCallback 被调用了两次?

标签 javascript html web-component custom-element

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

Screenshot

关于javascript - 为什么 attributeChangedCallback 被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718254/

相关文章:

javascript - 通过拖动移动动态创建的 DIV

javascript - Python:登录到网页并单击没有 Selenium 的按钮

javascript - 如何为所有实例设置相同的子组件动态宽度?网络组件

javascript - 如何将数组从主机绑定(bind)到 child

javascript - 视差滚动背景图像自动放大和缩小

javascript - npm 找不到文件

php - 如何让我的 Logo 链接回到 wordpress 22 子主题中的主页?

javascript - 如何使用 Shadow DOM v1 从影子根访问宿主元素?

javascript - 调用回调时未捕获类型错误

javascript - 基本 JavaScript 验证不起作用