在Polymer 1.0中绑定文本环绕元素

ale*_*esc 11 javascript data-binding mutation-observers polymer-1.0

我用Polymer创建了一个自定义Web组件,它包装文本并稍微改变它(在这个概念证明中转换为大写).

元素本身可以与静态内容一起使用.但是,当内容动态绑定时,组件无法显示内容.

例如:

<my-wrapper>Hello, World!</my-wrapper> <!-- Works -->
<my-wrapper>[[someText]]</my-wrapper> <!-- Doesn't work -->
Run Code Online (Sandbox Code Playgroud)

目前我正在使用observeNodes,它设法触发初始文本转换,但无法触发子顺序更改.

我目前的原型定义为:

<dom-module id="my-wrapper">
  <template>
    <span id="placeholder"></span>
  </template>
  <script>
    Polymer({
      is: 'my-wrapper',
      ready: function() {
        var self = this;
        Polymer.dom(Polymer.dom(this)).observeNodes(function(info) {
          self.$.placeholder.textContent = info.target.textContent.toUpperCase();
        });
        /*var mutationObserver = new MutationObserver(function(e) {
          console.log(e);
        });
        mutationObserver.observe(this.root, {characterData: true, childList: true});*/
      },
    });
  </script>
</dom-module>
Run Code Online (Sandbox Code Playgroud)

可以在这里找到针对上述问题的工作JSBin:http://jsbin.com/jumewuzuho/1/edit?html,console,output.

关于如何捕获(轻DOM)内容的变化的任何建议,以便我可以重新转换文本?

正如你在注释的代码块中看到的那样,我已经尝试过使用MutationObserver,但是无法创建一个工作原型.我的猜测是我没有使用正确的节点(this.root在我的情况下).

And*_*ves 1

我不认为ObserveNodes(或MutationObserver) 是解决这个问题的最佳方法。ObserveNodes跟踪子节点何时添加到元素中以及何时从元素中删除。

在你的例子中,DOM 节点没有被添加或删除,它只是元素的内部文本发生了变化。这些更改不会被ObserveNodes.

我会推荐另一种方法,在我看来,它更符合聚合物的做事方式,使用标签content

为了支持元素的 light DOM 与其本地 DOM 的组合,Polymer 支持内容元素。该content元素提供了一个插入点,在此元素的 light DOM 与其本地 DOM 相结合

我将使用内容标签创建一个插入点,然后通过 Shadow DOM 对其进行样式设置(文本转换:大写):

<dom-module id="my-wrapper">
  <template>
    <style>
      :host {
        text-transform: uppercase;
      }
    </style>
    <content></content>
  </template>
  <script>
    Polymer({
      is: 'my-wrapper'
    });
  </script>
</dom-module>
Run Code Online (Sandbox Code Playgroud)