【问题标题】:What is the Correct way of listening ObservableList adding and removing?监听 ObservableList 添加和删除的正确方法是什么?
【发布时间】:2015-04-09 12:31:10
【问题描述】:

我有下一个代码:

@CustomTag('my-element')
class MyElement extends PolymerElement {
  MyElement.created() : super.created();

  @published ObservableList persons = toObservable([]);

  handleAdd() {
    persons.add({'name': 'jhon', 'lastName': 'Doe'});
  }

  handleRemove() {
    persons.remove({'name': 'jhon', 'lastName': 'Doe'});
  }
}

这是 HTML:

<polymer name="my-element">
  <template>
    <template repeate="{{p in persons}}">
      {{p['name']}} {{p['lastName']}}
    </template>
    <button on-click="{{handleAdd}}">add person</button>
    <button on-click="{{handleRemove}}">remove person</button>
  <template>
</polymer>

在调试时,它会从内部对象列表中添加和删除。但是,它从不显示 HTML 中添加的元素。

【问题讨论】:

    标签: dart dart-polymer observablelist


    【解决方案1】:

    此代码行无效

    persons.remove({'name': 'jhon', 'lastName': 'Doe'});
    

    因为

    print({'name': 'jhon', 'lastName': 'Doe'} == {'name': 'jhon', 'lastName': 'Doe'});
    

    试试DartPad

    打印 false 因为对于集合 Dart 比较的是身份而不是内容。 有可用的助手。见How can I compare Lists for equality in Dart?

    你可以做的是

    persons.removeWhere((p) => p['name'] == 'jhon' && p['lastName'] == 'Doe');
    

    试试DartPad

    这不起作用,因为在 Dart 中,您无法使用点符号访问 Map 的元素

    <template repeate="{{p in persons}}">
      {{p.name}} {{p.lastName}}
    </template>
    

    如果你把它改成

    <template repeate="{{p in persons}}">
      {{p['name']}} {{p['lastName']}}
    </template>
    

    它应该按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 2016-05-27
      • 1970-01-01
      • 2013-12-06
      相关资源
      最近更新 更多