我一直在使用polymer.dart教程中的秒表示例。我已将@Observable String counter = '00:00';
更改为:
String _counter = '00:00';
@published void set counter (String s){ _counter = s; }
@published String get counter => _counter;
我将它设置为@published
所以我可以在html标记中设置counter属性,当我最初将其更改为@Published String counter = '00:00';
但将其拆分为单独的getter和setter属性时,这非常有用根本不再有效,是否可以做这样的事情?我希望在以编程方式或通过用户/ html更改更改绑定值时执行一些自定义逻辑。
答案 0 :(得分:2)
@observable
仅在吸气剂上是必需的。
我想你想做的是
// additional functionality in the setter
String _counter = '00:00';
@PublishedProperty(reflect: true)
String get counter => _counter;
void set counter (String s){
_counter = s;
// do something ...
}
void attached() {
new async.Timer.periodic(new Duration(seconds:1), (_) {
var oldVal = _counter;
var time = new DateTime.now();
_counter = '${time.minute}:${time.second}';
// explicitely notify Polymer about the changed value
notifyPropertyChange(#counter, oldVal, _counter);
});
}
或者
// additional functionality in xxxChanged
@PublishedProperty(reflect: true)
String counter = '00:00';
void counterChanged(oldVal, newVal){
// do something ...
}
另一个是
// use readValue/writeValue to fix some timing issues
@PublishedProperty(reflect: true)
String get counter => readValue(#counter);
void set counter (String s){
writeValue(#counter, s);
// do something ...
}
//in the constructor
writeValue(#counter, '00:00');
@PublishedProperty(reflect: true)
确保使用字段值更新HTML属性。
如果你发现这令人困惑,你并不孤单......