我有一个对象列表(例如,人),我在列表中动态添加和删除。我想在列表中的任何项目上更改某个属性时在列表中运行查询。
例如,我想知道列表中的任何对象是否更改了其“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;
}
}
答案 0 :(得分:5)
输入:ListPathObserver
!
添加此构造函数:
MyElement() {
ListPathObserver observer = new ListPathObserver(people, 'signedAgreement');
observer.changes.listen((_) => notifyProperty(this, const Symbol('signedCount')));
}
此处,当observer
中的任何人更改people
属性时,signedAgreement
会触发。
然后,在回调中,我们通知观察者系统应该查看signedCount
。