本文介绍了如何使用Polymer-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;
  }
}


推荐答案

输入: ListPathObserver

添加此构造函数:

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

此处,观察者个人中的任何人更改其 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.

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

09-02 03:57