Günter Zöchbauer
Günter Zöchbauer

Reputation: 657268

Observe changes to properties of items in a list in Polymer 1

I have a property

  @property final List<Item> items = [
    new Item('red', false),
    new Item('green', true),
    new Item('blue', false)
  ];

where class Item looks like

class Item extends JsProxy {
  @reflectable String color;
  @reflectable bool checked;
  Item(this.color, this.checked);
}

The HTML looks like

  <template is="dom-repeat" items="{{items}}">
    <label><span>{{item.color}}</span>
      <input type="checkbox"
             value="{{item.color}}"
             checked="{{item.checked::change}}">
    </label>
  </template>

I want to be notified when checked in any of the items was changed.

Upvotes: 2

Views: 202

Answers (1)

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

Reputation: 657268

An observer can be set up using the @Observe('some.path') annotation. If the path contains a .*, the handler is called with a change record which contains the actual path of the change.

@Observe('items.*')
  void updateSelectedColors(Map record, [_]) {
    String path = record['path'];
    if (path == 'items' || path.endsWith('.checked')) {
      // do something
    }
  }
}

path == 'items' applies for the initialization of the items property with the default value. path.endsWidth('.checked') ensures that the code (// do something) is only executed when actually the checked property was changed. All other changes are ignored.

Upvotes: 1

Related Questions