【问题标题】:Why is attributeChangedCallback called twice?为什么attributeChangedCallback被调用了两次?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我查看了您的 jsfiddle,它实际上并没有在单击按钮时调用两次,而是在呈现 &lt;my-component id="compo" foo="bar"&gt;&lt;/my-component&gt; 时第一次调用,因为您正在设置 foo 的值;其次,当您单击按钮时。

    你也可以在jsfiddle上调试,使用开发者工具,按Ctrl+Shift+F找到并调试函数。

    【讨论】:

    • 谢谢。我已经在最新版本的 Chrome 上测试了我的 JsFiddle,并且确实只进行了一次调用。在我的专业计算机上,我使用的是 Chrome v53,它 实现了 customElements(在 v54 中添加),因此使用了 polyfill 并且 那里,进行了调用两次。所以问题出在 polyfill 上!
    猜你喜欢
    • 2013-11-20
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2012-08-02
    相关资源
    最近更新 更多