Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Using observable with multiple getter/setter(s)

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

like image 603
user3338276 Avatar asked Oct 21 '22 13:10

user3338276


2 Answers

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.

like image 154
nunobaba Avatar answered Oct 24 '22 01:10

nunobaba


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

like image 45
Anders Avatar answered Oct 23 '22 23:10

Anders