用于观察的聚合物代码示例片段不会更改文本颜色

Polymer code sample snippet for observe does not change text color

本文关键字:颜色 文本 片段 观察 聚合物 代码 用于      更新时间:2023-09-26

你好互联网的善良人士,

我正在尝试使用聚合物示例片段,但似乎无法获得以下片段示例以使观察正常运行:

<link rel="import" href="../../components/polymer/polymer.html">
<polymer-element name="my-element">
   <template>
     <div>{{thing.color}}</div>
     <button on-tap="{{changeColor}}">Change color</button>
     <p>{{message}}</p>
   </template>
 <script>
    Polymer({
      message: '',
      created: function() {
        this.thing = {
          color: 'red'
        };
      },
      observe: {
        'thing.color': 'colorObserver',
      },
      colorObserver: function(oldValue, newValue) {
        this.message = 'Color changed from ' + oldValue + ' to ' + newValue;
      },
      changeColor: function(e) {
        this.thing.color = this.thing.color === 'red' ? 'green' : 'red';
      }
    });
  </script>
 </polymer-element>

。"红色"或"绿色"文本的颜色不会切换,但消息文本显示"正常"。

指向我遇到此小问题的特定 Polymer 代码示例片段的链接在这里: https://github.com/PolymerLabs/polymer-patterns/blob/master/snippets/observing-changes/watching-for-changes-to-a-nested-object.html

我在 Chrome 开发编辑器中使用示例代码段模板,再次:网页按钮工作正常,显示文本正常,但可惜,文本颜色"红色"或"绿色"没有显示。 我已经对组件包运行了 bower 更新,并且 JavaScript 控制台中没有错误。

注意:还有另一个聚合物片段模板可以做一些非常相似的事情(切换文本颜色(,效果很好,链接在这里:

https://github.com/PolymerLabs/polymer-patterns/blob/master/snippets/basics/binding-to-a-style.html

<polymer-element name="my-element">
  <template>
    <p>My favorite color is <span style="color:{{color}}">{{color}}</span>.</p>
    <button on-tap="{{toggleColor}}">Toogle color</button>
  </template>
 <script>
  Polymer({
    color: 'red',
    toggleColor: function() {
      this.color = this.color === 'red' ? 'green' : 'red';
    }
  });
</script>

所以,在这一点上,我不相信我理解观察功能是如何工作的,作为一个元问题:任何人都可以建议如何解决此类问题吗? 和 - 或向我指出可能有助于此类故障排除的资源?(鉴于没有抛出明显的错误(。

提前致谢

那是因为你没有"实际上"thing.color绑定到适当的css属性:

<div style="color: {{thing.color}}">{{thing.color}}</div>