对于我的Polymer应用程序,我需要一个可观察的两种不同的类型,例如整数值和字符串值.我使用getter和setter来封装状态和内部表示.通过这样做,我必须为每个setter中的每个observable 实现notifyPropertyChange,这导致了很多errorprone管道代码.例如,我需要两次notifyPropertyChange -Statements两种口味,如果我必须使用4种口味,我必须使用4*4 = 16 notifyPropertyChange -Statements.我修改了点击计数器示例来说明这一点:
@CustomTag('click-counter')
class ClickCounter extends PolymerElement {
int _count;
@observable int get count => _count;
@observable set count(int val) {
notifyPropertyChange(#count,_count,val);
_count = notifyPropertyChange(#strcount,_count,val);}
@observable String get strcount {
print("TOSTRING "+_count.toString());
return _count.toString();}
@observable set strcount(String val) {
notifyPropertyChange(#strcount,_count,int.parse(val));
_count = notifyPropertyChange(#count,_count,int.parse(val));}
ClickCounter.created() : super.created() {
}
void increment() {
count++;
}
}
Run Code Online (Sandbox Code Playgroud)
没有那么多notifyPropertyChange -Statements,有没有更好的方法来实现它?
问候
马库斯
我还没有测试过它,但它应该可以工作,而且我认为如果你有更多这样的属性,它的代码会显着减少。
@CustomTag('click-counter')
class ClickCounter extends PolymerElement {
int _count;
@observable int get count => _count;
set count(int val) {
notifyPropertyChange(#count,_count,val);
notifyPropertyChange(#strcount, _count.toString(), val.toString());
_count = val;
@observable String get strcount {
// print("TOSTRING "+_count.toString());
return _count.toString();}
set strcount(String val) {
count = int.parse(val); // set the new value using the setter not the field to fire property change
}
ClickCounter.created() : super.created();
void increment() {
count++;
}
}
Run Code Online (Sandbox Code Playgroud)