首页 > 解决方案 > 使用 Polymer Templatizer 标记模板

问题描述

如果需要,我想添加模板的内容,并在不需要时将其删除。我的代码基于聚合物的 dom-if 实现

这是添加模板内容的代码

if (!this.ctor) {
  this.templatize(this);
}  
if (parentNode) {
  const parent = Polymer.dom(parentNode);
  if (!this._instance) {
    this._instance = this.stamp();
    const targetNode = parent.firstElementChild;
    const newNode = this._instance.root;
    parent.insertBefore(newNode, targetNode);
  } else {
    const children = this._instance._children;
    if (children && children.length) {
      const lastChild = Polymer.dom(this).previousSibling;
      if (lastChild !== children[children.length - 1]) {
        for (let i = 0, node; i < children.length && (node = children[i]); i++) {
          parent.insertBefore(node, this);
        }
      }
    }
  }
}

这是删除模板内容的代码:

if (this._instance) {
  const children = this._instance._children;
  if (children && children.length) {
    const parent = Polymer.dom(Polymer.dom(children[0]).parentNode);
    for (let i = 0, n; i < children.length && (n = children[i]); i++) {
      parent.removeChild(n);
    }
  }
  if(this.restamp) {
    this._instance = null;
  }
}

因此,如果我将 restamp 属性设置为 true 一切正常。但是,如果我将其设置为 false,则不会显示某些内容。

上面的代码中不会插入 dom-repeate 模板的内容

parent.insertBefore(node, this);

因为 node 只包含 #document-fragments 而不是 dom-repeat 插入的内容。

我试图达到正确的内容,但我失败了。是否有可能插入正确的内容,即使它包含 dom-repeat、dom-if 等?

谢谢

标签: javascriptpolymer-1.0

解决方案


推荐阅读