【问题标题】:How to access polymer properties in observer function如何在观察者函数中访问聚合物属性
【发布时间】:2015-11-30 12:06:13
【问题描述】:

当我尝试将“progressbar.js”包装在聚合物元素中时,我无法访问 circleprop。

var startColor = '#FC5B3F';
var endColor = '#6FD57F';

Polymer({
  is: "home-view",
  properties: {
    value: {
      type: String,
      observer: '_valueChanged'
    },
    circleProp: {
      type: Object,
      notify: true,
     reflectToAttribute: true
    }
  },

  ready: function() {
    var element = this.$$('#circleValue');
    this.circleProp = new ProgressBar.Circle(element, {
      color: startColor,
      trailColor: '#eee',
      trailWidth: 1,
      duration: 2000,
      easing: 'easeInOut',
      strokeWidth: 5,
      text: {
          value: '0'
      },

      // Set default step function for all animate calls
      step: function(state, circle) {
          circle.path.setAttribute('stroke', state.color);
          circle.setText((circle.value() * 100).toFixed(0));
      }
  });

  this.circleProp.animate(0.3, {
      from: {color: startColor},
      to: {color: endColor}
  });
},

attach : function() {
  if (this.circleProp) {
      this.circleProp.animate(this.value, {
          from: {color: startColor},
          to: {color: endColor}
      });
  }
},

_valueChanged : function(oldValue, newValue) {
  if (this.circleProp) {
    this.circleProp.animate(newValue, {
        from: {color: startColor},
        to: {color: endColor}
    });
  }
}
});

如何访问 circleProp 以便制作动画。或者如何访问 _valueChanged 中的对象?只能访问该元素的 DOM。

【问题讨论】:

  • 你应该可以使用this关键字访问,结帐this out。
  • _valueChanged 可能在准备好之前运行,Polymer 很奇怪。尝试从控制台手动运行它并在其中放置一个 console.log(this.circleProp) 以查看发生了什么

标签: javascript polymer polymer-1.0


【解决方案1】:

我认为您的问题是 circleProp 属性上的 reflectToAttribute。你为什么这样做? Polymer 正在尝试将其序列化为 dom 中元素的属性。

否则访问this.circleProp 会起作用

【讨论】:

  • 当我从代码中删除它时它也不起作用,在执行 console.log 时它会打印出一个“DOM”元素。
  • this.circleProp 未定义......看起来 _changedValue 失去了他的上下文,只绑定到 Dom 元素本身
【解决方案2】:

_valueChanged 在准备好之前肯定会被调用。尝试一个复杂的观察者

observers: ['_valueCahnged(value)']

这将防止观察值未定义。同样在写入属性时使用

this.set('circleProp', newValue)

否则 Polymer 不会注意到发生了变化。在 _valueCahnged 观察者中,您可以通过此访问所有属性

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2017-03-13
    • 2016-10-25
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多