【问题标题】:Polymer 1.0 template bind ref equivalentPolymer 1.0 模板绑定参考等效项
【发布时间】:2015-05-28 20:41:30
【问题描述】:

在 Polymer 0.5 中,您可以这样做:

<template bind ref="howdyTpl"></template>
...
<template id="howdyTpl">Howdy {{whatever}}</template>

ID 为“howdyTpl”的模板将在ref 属性中引用的位置被标记。

如何在 Polymer 1.0 中做类似的事情?

【问题讨论】:

    标签: polymer


    【解决方案1】:

    这是一个执行类似操作的自定义元素。

    Polymer({
      is: 'bind-ref',
    
      properties: {
        ref: {
          type: String,
          observer: 'refChanged',
        },
      },
    
      refChanged: function(newRef, oldRef) {
        if (oldRef != undefined) {
          this._removeChildren();
          this._stamp();
        }
      },
    
      _stamp: function() {
        this._parent = Polymer.dom(this).parentNode;
        var rootEl = this._parent;
        while (Polymer.dom(rootEl).parentNode) {
          rootEl = Polymer.dom(rootEl).parentNode;
        }
    
        var tpl = Polymer.dom(rootEl).querySelector('#' + this.ref);
        var tplRoot = tpl.stamp().root;
        this._children = Array.prototype.slice.call(tplRoot.childNodes);
        Polymer.dom(this._parent).insertBefore(tplRoot, this);
      },
    
      _removeChildren: function() {
        for (var i = 0; i < this._children.length; i++) {
          Polymer.dom(this._parent).removeChild(this._children[i]);
        }
      },
    
      attached: function() { this._stamp(); },
      detached: function() { this._removeChildren(); },
    });
    

    目标模板元素必须是dom-template 元素。

    <bind-ref ref="howdyTpl"></bind-ref>
    <template is="dom-template" id="howdyTpl">Howdy <span>{{whatever}}</span></template>
    

    (代码 sn-ps 许可Apache 2.0。)

    【讨论】:

    • 很遗憾,但是当 bind-ref 和 template 都是兄弟姐妹时,这才有效。如果 bind-ref 在
    • @miyconst 在dom-repeat 内对我来说工作正常。你看到什么问题?另外,我刚刚修复了它,以便在分离时移除标记的元素。
    • 我正在尝试制作一个自定义数据网格组件。用户应该能够为列定义自定义模板。在这里可以找到草稿:miyconst.github.io/ct-data-grid Actions 列有一个使用 bind-ref 的模板,但绑定在里面不起作用。
    【解决方案2】:

    I've created an element that resolves this problem. 这是一种 hack,但它可以工作...包括提供的其他答案无法处理的多深度文件包含和数据绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多