5

I can't figure out how to use the @observable annotation/Observable class to get simple notifications when the state of an object changes.

import 'package:web_ui/observe.dart';

@observable class T{
  String x;
// what else is needed?
}

T t = new T();
observe(t, (e) => print ("Value changed"));
t.x = "Changed";

I would like to use the observables without the rest of web-ui if possible (as a substitute for backbone.js).

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
mme
  • 167
  • 1
  • 8

2 Answers2

2

You will need to run the dwc compiler, which looks for @observable and generates new source code that actually implements the observing. I've never tried to run the observables without Web UI, but you'll certainly need dwc to generate the correct output.

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
0

I just spent some time trying to do the same thing. As stated in the answer above you cannot use the @observable annotation without WebUI/Polymer. You can however use the observable package. Here is a quick example:

import 'package:observe/observe.dart';

void main() {
  var person = new Person(18, false);

  person.changes.listen((List<ChangeRecord> changes) {
    changes.forEach((PropertyChangeRecord change) {
      print("$change");
    });
  });

  person.changes.listen((List<ChangeRecord> changes) {
    changes.where((PropertyChangeRecord c) => c.name == #employed).forEach((PropertyChangeRecord change) {
      print("Employment status changed!");
    });
  });

  print("start changing");

  person.age =  19;
  person.age =  19;
  person.age =  19;
  person.age = 20;
  person.employed = true;
  person.age = 21;
  person.age = 22;

  print("finish changing");
}

class Person extends ChangeNotifier {

  int _age;
  int get age => _age;
  void set age (int val) {
    _age = notifyPropertyChange(#age, _age, val);
  }

  bool _employed;
  bool get employed => _employed;
  void set employed (bool val) {
    _employed = notifyPropertyChange(#employed, _employed, val);
  }

  Person(this._age, this._employed);
}

The events are asynchronous so be careful if you are relying on the order of these events. The output of the above program is

start changing
finish changing
#<PropertyChangeRecord Symbol("age") from: 18 to: 19>
#<PropertyChangeRecord Symbol("age") from: 19 to: 20>
#<PropertyChangeRecord Symbol("employed") from: false to: true>
#<PropertyChangeRecord Symbol("age") from: 20 to: 21>
#<PropertyChangeRecord Symbol("age") from: 21 to: 22>
Employment status changed!
Ian
  • 490
  • 6
  • 16