Luis Vargas
Luis Vargas

Reputation: 2524

What is the Correct way of listening ObservableList adding and removing?

I have next code:

@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'});
  }
}

and this is the 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>

when debugging, it is added and removed from the internal list of objects. However, it never shows the elements as added in HTML.

Upvotes: 0

Views: 150

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657466

This code line has no effect

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

because

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

try at DartPad

prints false because for collections Dart compares identity not content. There are helpers available. See How can I compare Lists for equality in Dart?

What you can do instead is

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

try at DartPad

This doesn't work because in Dart you can't access elements of a Map using dot-notation

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

If you change this to

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

it should work as intened.

Upvotes: 1

Related Questions