如何使用Dart监听列表中的对象的属性更改? [英] How can I listen for changes to properties on objects inside a list, with Dart?

查看:860
本文介绍了如何使用Dart监听列表中的对象的属性更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表(例如,人),我动态添加和从列表中删除。

I have a list of objects (for example, people), and I dynamically add and remove from the list. I want to run a query across the list when a certain property changes on any item in the list.

例如,我想知道列表中是否有任何对象其signedAgreement属性已更改。我不想手动附加监听器到每个对象,我只想问列表。我如何做到这一点?

For example, I want to know if any object in the list has its "signedAgreement" property changed. I don't want to manually attached listeners to each object, I just want to ask the list. How can I do this?

我的代码:

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;
  }
}


推荐答案

Enter : ListPathObserver

添加此构造函数:

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

这里, observer 将在中的任何人的 signedAgreement 属性更改时触发。

Here, observer will fire when any person in people has its signedAgreement property changed.

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

Then, in the callback, we notify the observer system that it should go look at signedCount.

这篇关于如何使用Dart监听列表中的对象的属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆