在 Polymer 1.0 中动态注入模板

Dynamically injecting a template in Polymer 1.0

我正在尝试将 <template> 以正确的方式 注入并显示到 Polymer Webapp 中,但我遇到了一些困难。 (……或者我误解了 1.0 文档?)

documentation about manipulation the DOM 说:

Polymer provides a custom API for manipulating DOM such that local DOM and light DOM trees are properly maintained. These methods and properties have the same signatures as their standard DOM equivalents, except that properties and methods that return a list of nodes return an Array, not a NodeList.

Note: All DOM manipulation must use this API, as opposed to DOM API directly on nodes.

所以我想我必须到处使用 Polymer.dom API 来操纵 DOM,这对我来说很有意义,因为这样 Polymer 可以与生成的 shady 保持同步DOM。没有 DOM.appendChild(),而是 Polymer.dom().appendChild()。直接操纵阴暗的 DOM 不是一个好主意……或者会吗?

想象一个简单的页面结构:

<body>
  <template is="dom-bind" id="app">
    <main>
      <template is="dom-bind" id="content">
        <p>Lorem ipsum dolor sit amet.</p>
      </template>
    </main>
  </template>
</body>

还有第二个小片段,我可以将其导入到页面中。

<template id="snippet">
  <p>Consectetur adipisici elit.</p>
</template>

此模板应 replaced/referenced 与 #content。那么,让我们开始吧。

导入代码段很容易。我可以获取它并获取它的 DOM 元素。

Polymer.Base.importHref('/snippet', function(e) {
  // on success: imported content is in e.target.import

  var template = Polymer.dom(e.target.import).querySelector('#snippet');
  // until here it works, `template` is the template from my snippet
  ...

现在我想我必须将其附加到我的 template#app 并将 template#contentref 更改为 content... 如果更改 ref 是还支持吗?我该怎么做呢?无论我如何处理,我每次都会卡住。

var app = Polymer.dom(this).querySelector('#app'); // Works, is template#app
var app = document.querySelector('#app'); // Same result

Polymer.dom(app).appendChild(template); // will append it, but outside of the document fragment
Polymer.dom(app.root).appendChild(template); // won't do anything

Polymer.dom(app).querySelector('template'); // undefined
Polymer.dom(app.root).querySelector('template'); // undefined
app.querySelector('template'); // undefined

我花了很多时间研究这个问题,试图找到解决方案。它适用于标准 DOM API,但我认为这不是正确的方法。如果有人能解决我的困惑,那就太好了。

编辑: 还是 Polymer.dom(this) 会做这件事,我不需要打电话给 Polymer.dom(app)?但是,我又试过了,但还是不行。啊啊啊啊,真是一头雾水。

如果我没有理解错,并且您想将模板插入到本地 dom(将它插入其他地方并没有多大意义),那么它是 Polymer.dom(this.root).appendChild

From https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#dom-api: 为了insert/append变成自定义元素的局部dom,使用this.root作为父元素。