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

Reputation: 657268

How to notify Polymer about changes to a field in a collection of objects

Currently I have

@property List<DemoItem> demos = 
  [new DemoItem('a'), new DemoItem('b'), new DemoItem('c')];

...

@reflectable
void clickHandler([_, __]) {
  demos.firstWhere((d) => d.name == 'b').isActive = true);
  notifyPath('demos', demos);
}

...

class DemoItem extends JsProxy {
  @reflectable
  bool isActive = false;
  @reflectable
  final String name;
  @reflectable
  DemoElementItem(this.name);
}

html

<template is="dom-repeat" items="[[demos]]" as="demo" >
  <paper-item active="[[demo.isActive]]">
    <div data-demo-name$="[[demo.name]]" 
      on-click="clickHandler">[[demo.name]]</div>
  </paper-item>
</template>

But the active state of the <paper-item> isn't updated, so this doesn't work and also doesn't seem very efficient. How to do this right?

Upvotes: 0

Views: 79

Answers (1)

Jake MacDonald
Jake MacDonald

Reputation: 1348

You need to notify the exact path that changed, since the list itself is the same instance the notification is actually ignored otherwise. For example here is one option for the clickHandler, although not the most efficient:

@reflectable
void clickHandler([_, __]) {
  var demo = demos.firstWhere((d) => d.name == 'b')..isActive = true;
  notifyPath('demos.${demos.indexOf(demo)}.isActive', demo.isActive);
}

Upvotes: 1

Related Questions