聚合物1.0元素的动态类

kaz*_*mer 6 javascript polymer polymer-1.0

我创建了这个组件来演示我的问题.正如预期的那样,这个组件在chrome和firefox中工作.但如果我写this.$.wrapper.setAttribute('class','blue');而不是this.$.wrapper.setAttribute('class','blue style-scope poly-test');它停止在Firefox中工作.

这是在事件处理程序中更改阴影dom元素上的类的首选方法,还是我在做一些意外正确的事情,这可能会在未来的版本中破坏?

另外,为什么我必须style-scope手动为firefox 指定和我的元素名称?

<link rel="import" href="../js/bower_components/polymer/polymer.html">
<dom-module id="poly-test">
  <style>
    .blue { border: 10px solid blue; }
    .red  { border: 10px solid red; }
    #wrapper { font-weight: bold; font-size: 42px; }
  </style>
  <template>
    <div id="wrapper" class="red"><content></content></div>
  </template>
</dom-module>
<script>
  Polymer({
    is: 'poly-test',
    properties: {'blue': { type: 'Boolean', value: false }},
    listeners: { 'click': 'clickHandler' },
    clickHandler: function () {
      this.blue = !this.blue;
      if (this.blue) {
        this.$.wrapper.setAttribute('class','blue style-scope poly-test');
      } else {
        this.$.wrapper.setAttribute('class','red  style-scope poly-test');
      }
      this.updateStyles();
    }
  });
</script>
Run Code Online (Sandbox Code Playgroud)

zer*_*evx 9

Web组件的想法是使Web尽可能具有声明性.本着这种精神,聚合物实现动态类的方式应该是

声明性方法:(https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#native-binding)

...
<dom-module id="poly-test">
  ...
  <template>
    <!-- handle dynamic classes declaratively -->
    <div class$="{{computeClass(isBlue)}}">
      <content></content>
    </div>
  </template>
</dom-module>
<script>
  Polymer({
    is: 'poly-test',
    properties: {
      'isBlue': { type: Boolean, value: false }
    },
    listeners: { 'click': 'clickHandler' },
    clickHandler: function () {
      this.isBlue = !this.isBlue;
    },
    computeClass: function (f) {
      return f ? "blue" : "red";
    }
  });
</script>
Run Code Online (Sandbox Code Playgroud)

style-scope 在升级元素和将节点标记为DOM时(在我认为的阴暗行为下),框架使用它,我认为我们不打算触摸它.

如果你真的希望强制处理,我建议使用Polymer API的toggleClass()方法.

势在必行的方法:(http://polymer.github.io/polymer/)

...
<dom-module id="poly-test">
  ...
  <template>
    <div id="wrapper" class="red"><content></content></div>
  </template>
</dom-module>
<script>
  Polymer({
    is: 'poly-test',
    properties: {
      'isBlue': { type: Boolean, value: false }
    },
    listeners: { 'click': 'clickHandler' },
    clickHandler: function () {
      this.isBlue = !this.isBlue;
      this.toggleClass("blue", this.isBlue, this.$.wrapper);
      this.toggleClass("red", !this.isBlue, this.$.wrapper);
    }
  });
</script>
Run Code Online (Sandbox Code Playgroud)