for my Polymer application I need one observable in two different flavors, for example as an integer-value and and string-value. I use getters and setters to encapsulate the state and internal representation. By doing this I have to implement notifyPropertyChange for every observable in every setter, which leads to much errorprone plumbing code. For example
I need two times to notifyPropertyChange-Statements for two flavors, if I have to use
4 flavors, I have to use 4*4 = 16 notifyPropertyChange-Statements. I have modified the click-counter example to illustrate this:
@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++;
}
}
Is there a better way to implement this without so much notifyPropertyChange-Statements?
Regards
Markus
In case the count
property doesn't need to be private — something to consider according to the Dart style guide — a sweet option would be available for this kind of situation.
class ClickCounter extends PolymerElement {
@observable int count;
...
void countChanged(oldValue) {
// do something...
}
}
Changes occurred to observable properties is automatically passed on method named as <property_name>Changed
where property_name refers to the property to spy on.
Hope this help bring more fun to writing Polymer components.
Not sure if this applies to you but I had the same problem. In my case though I could solve it with just the one property and a filter.
dart class
int count;
int asInt(...) // can't remember details of filters
html
<input type="text">{{count | asInt}}<input>
Apologies for the incorrectness of the code. I'm on my phone and don't have time to search the code. Hopefully you get the idea
Cheers
Anders
I have not tested it, but it should work and I think its notable less code if you have more such properties.
@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++;
}
}