【问题标题】:How do I bind a CSS class to an observable object or property in Polymer?如何将 CSS 类绑定到 Polymer 中的可观察对象或属性?
【发布时间】:2013-10-02 19:28:37
【问题描述】:

如果某个条件为真,我希望将 CSS 类应用于元素,并在条件变为假时删除该类。这是网络编程中非常常见的模式,我想知道使用 Polymer 的惯用方式。

【问题讨论】:

    标签: dart dart-polymer polymer


    【解决方案1】:

    bindCssClass 已弃用(从 Polymer 0.10.0-pre.4 开始)

    CSS 类现在可以绑定到地图。

    @observable var btnClasses = toObservable({'someclass': true, 'someotherclass': false});
    
    <polymer-element name="spark-button" class="{{btnClasses}}">
      <template>
        ...
    </polymer-element>
    

    【讨论】:

      【解决方案2】:

      这个答案不再有效。请改用接受的答案。

      使用bindCSSClass 有条件地将 CSS 类绑定到元素。在下面的点击计数器示例中,“蓝色”类应用于显示计数器值的元素,前提是该值可被三整除:

      import 'package:polymer/polymer.dart';
      
      @CustomTag('click-counter')
      class ClickCounter extends PolymerElement with ObservableMixin {
        @observable int count = 0;
      
        void increment() {
          count++;
        }
      
        ClickCounter() {
          bindProperty(this, const Symbol('count'),
              () => notifyProperty(this, const Symbol('divByThree')));
        }
      
        bool get divByThree => count % 3 == 0;
      
        void created() {
          super.created();
          var root = getShadowRoot("click-counter");
          var item = root.query('#click-display');
          bindCssClass(item, 'blue', this, 'divByThree');
        }
      }
      

      在示例中,我们使用 getter 来检查值是否可以被 3 整除:

        bool get divByThree => count % 3 == 0;
      

      然后我们为 getter 创建一个 observable 绑定:

        ClickCounter() {
          bindProperty(this, const Symbol('count'),
              () => notifyProperty(this, const Symbol('divByThree')));
        }
      

      然后,在 'created()` 中,我们找到应用了 CSS 类(和未应用)的元素:

          var root = getShadowRoot("click-counter");
          var item = root.query('#click-display');
      

      我们使用 bindCssClass 将 CSS 类绑定到基于返回布尔值的 divByThree getter 的元素:

          bindCssClass(item, 'blue', this, 'divByThree');
      

      在这种情况下,当divByThree 返回 true 时,'blue' 类被应用到元素上,而当它返回 false 时被取消应用。

      bindCssClass 定义在observe 包中的html.dart

      您可以在https://github.com/shailen/dartythings/tree/master/bindCSS 看到使用此代码的完整应用程序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-12
        • 2020-06-05
        • 1970-01-01
        • 2017-07-22
        • 2021-11-22
        • 2015-03-05
        • 1970-01-01
        • 2017-09-05
        相关资源
        最近更新 更多