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

Issue

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.

Solution

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.

Answered By – Günter Zöchbauer

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.