gpt4 book ai didi

Dart:将 observable 与多个 getter/setter 一起使用

转载 作者:行者123 更新时间:2023-12-02 05:11:43 26 4
gpt4 key购买 nike

对于我的 Polymer 应用程序,我需要一个具有两种不同风格的可观察值,例如作为整数值和字符串值。我使用 getter 和 setter 来封装状态和内部表示。通过这样做,我必须为每个 setter 中的每个可观察值实现 notifyPropertyChange,这会导致很多容易出错的管道代码。例如如果我必须使用,我需要两次 notifyPropertyChange - 两种风格的语句4 种口味,我必须使用 4*4 = 16 个 notifyPropertyChange -语句。我修改了点击计数器示例来说明这一点:

@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++;
}
}

是否有更好的方法来实现这一点,而无需那么多 notifyPropertyChange 语句?

问候

马库斯

最佳答案

万一count属性(property)不需要是私有(private)的——根据 Dart style guide 需要考虑这一点— 对于这种情况,有一个不错的选择。

class ClickCounter extends PolymerElement {
@observable int count;
...
void countChanged(oldValue) {
// do something...
}
}

可观察属性发生的更改会自动传递到名为 <property_name>Changed 的方法上其中 property_name 指的是要监视的属性。

希望这有助于为编写 Polymer 组件带来更多乐趣。

关于Dart:将 observable 与多个 getter/setter 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21941265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com