观察聚合物飞镖包装

时间:2014-06-18 03:47:27

标签: dart dart-polymer

我试图使用observe包而不必在我的模型中有注释,只能通过在setter中提升notifyPropertyChange,所以要测试我做了以下测试

import 'package:observe/observe.dart';
import 'dart:async';
import 'dart:math';
void main() {

  var dummyWatchingModel = new DummyWatchingModel();
  new Timer.periodic(new Duration(milliseconds:1000), (_){
           //calls a function that set a random value to the property in the observable model
           dummyWatchingModel.setModelProps();
      });
}

class Model extends Observable{
  int _x;
  Model(this._x);

  int get x=> _x;
  void set x(int value){
    _x = notifyPropertyChange(#_x, _x, value);
  }
}

class DummyWatchingModel{
  Model model = new Model(1); 
  final rng = new Random(); 
  anotherModel(){

    //watch for changes in model instance properties
    this.model.changes.listen((List<ChangeRecord> records) {
      for(ChangeRecord change in records){
        print(change.toString());
      }
    });
  }

  //the callback for the timer to assign a random value model.x
  setModelProps(){
    model.x = rng.nextInt(100);
    print('called...');
  }
}

我正在使用引发notifyPropertyChange的setter更改Model实例中的属性值,但它从不会听取更改,不知道为什么?

1 个答案:

答案 0 :(得分:2)

我认为您希望使用ChangeNotifier代替Observable

我不确定notifyPropertyChange但是Observable您通常需要致电dirtyCheck以获得有关更改的通知。

前段时间我做了一个小例子来了解这两者是如何工作的:

import 'package:observe/observe.dart';

class Notifiable extends Object with ChangeNotifier {
  String _input = '';

  @reflectable
  get input => _input;

  @reflectable
  set input(val) {
    _input = notifyPropertyChange(#input, _input, val + " new");
  }

  Notifiable() {
    this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
  }
}

class MyObservable extends Observable {
  @observable
  String counter = '';

  MyObservable() {
    this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
  }
}

void main() {
  var x = new MyObservable();
  x.counter = "hallo";
  Observable.dirtyCheck();

  Notifiable notifiable = new Notifiable();
  notifiable.input = 'xxx';
  notifiable.input = 'yyy';
}