【问题标题】:Nested web component's `attachedCallback` not running on appended嵌套 Web 组件的“attachedCallback”未在附加时运行
【发布时间】:2015-05-29 13:45:48
【问题描述】:

我在玩 W3C Web 组件。

我有一个主页,其中包含组件 A:

<!-- homepage.html -->
<link rel='import' href='a.html'>
<component-a></component-a>

在组件 A 中,我包含另一个组件 B:

<!-- a.html -->
<link rel='import' href='b.html'>
<template>
  <component-b></component-b>
  <component-b></component-b>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('a')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-a', { prototype: proto })
  }()
</script>

B的代码和A很相似:

<!-- b.html -->
<template>
  <span>b</span>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('b')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-b', { prototype: proto })
  }()
</script>

奇怪的是,当页面加载时,我只能在控制台看到"a"。我期待"b" 也是两倍。并且组件 B 并没有真正被解析。

更奇怪的是,如果我在控制台中运行以下代码:

document.querySelector('component-a').innerHTML += ''

它突然给了我两次"b"

截图如下:

【问题讨论】:

    标签: html web-component custom-element


    【解决方案1】:

    朋友给我一个解决办法,用document.importNode代替cloneNode

    function getTemplate(selector) {
      // return currentDocument.querySelector(selector).content.cloneNode(true)
      return document.importNode(currentDocument.querySelector(selector).content, true)
    }
    

    而且效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-21
      • 2021-12-29
      • 1970-01-01
      • 2016-12-22
      • 2012-12-27
      • 2018-07-28
      • 2020-03-04
      • 1970-01-01
      相关资源
      最近更新 更多