7

我有一个对象列表(例如,人),我从列表中动态添加和删除。当列表中任何项目的某个属性发生更改时,我想在列表中运行查询。

例如,我想知道列表中的任何对象是否更改了其“signedAgreement”属性。我不想手动将侦听器附加到每个对象,我只想询问列表。我怎样才能做到这一点?

我的代码:

library my_element;

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'models.dart';

@CustomTag("my-element")
class MyElement extends PolymerElement with ObservableMixin {
  final List people = toObservable([]); // observe adds/removes to the list
  final Person newPerson = new Person();

  // How can I know when to re-evaluate signedCount?

  int get signedCount => people.where((Person p) => p.signedAgreement).length;

  void save(Event e, var detail, Node target) {
    people.add(new Person.from(newPerson));
    newPerson.blank();
  }
}

我的模型对象看起来像:

library models;

import 'package:polymer/polymer.dart';

class Person extends Object with ObservableMixin {
  @observable String name;
  @observable bool signedAgreement = false;

  Person();

  Person.from(Person other) {
    name = other.name;
    signedAgreement = other.signedAgreement;
  }

  blank() {
    name = '';
    signedAgreement = false;
  }
}
4

1 回答 1

5

输入:ListPathObserver

添加此构造函数:

  MyElement() {
    ListPathObserver observer = new ListPathObserver(people, 'signedAgreement');
    observer.changes.listen((_) => notifyProperty(this, const Symbol('signedCount')));
  }

在这里,observer当任何人在peoplesignedAgreement财产发生变化时会触发。

然后,在回调中,我们通知观察者系统它应该去查看signedCount

于 2013-09-25T00:40:06.180 回答