Reputation: 443
I have a Dart web app using Polymer 1.0. The main-app is displaying a list of items. The main-app can add items to that list and then some time later an AJAX call will return and update the state of the added item. The update methods will need to utilize the dart-polymer helper methods in order to notify polymer of the change. However, I don't see how to pass a reference to the dart-polymer helper methods for this update.
I have it working below by having the MyItem
element make the AJAX call at construction and then MyItem
update the item on return. This works because MyItem
only has a single item. However, this is not ideal because MyItem
always makes an AJAX call and cannot simply be used to display the state of item
if the page is reloaded.
I'm looking for a way to notify Polymer that an item has changed state that is contained somewhere in a list (the index is unknown).
main-app.html:
<dom-module id="main-app">
<paper-button on-tap="addItem>Add</paper-element>
<template is="dom-repeat" items="items" as="item">
<my-item item="{{item}}"></my-item>
</template>
</dom-module>
main-app.dart:
@PolymerRegister('main-app')
class MainApp extends PolymerElement {
final List<Item> items = [];
@reflectable
void addItem(Event e, Object detail) {
insert('items', 0, new Item());
}
}
my-item.html:
<dom-module id="my-item">
<template>
<div>{{item.state}}</div>
</template>
</dom-module>
my-item.dart:
@PolymerRegister('my-item')
class MyItem extends PolymerElement {
@property
Item item;
MyItem.create() : super.create();
ready() {
HttpRequest.postFormData("/items").then((HttpRequest request) {
set('item.state', request.responseText);
});
}
}
item.dart:
class Item extends JsProxy {
@reflectable
String state;
Item(this.state);
}
* Edit *
As Günter pointed out I could look up the item in the list and then remove and add it again. I wrote this function in main-app to be called on update:
void fireItemUpdate(Item item) {
int i = items.indexOf(item);
removeItem('items', item);
insert('items', i, item);
}
However, when I called that polymer did not render the updated item. I had to create a new item:
void fireItemUpdate(Item item) {
int i = items.indexOf(item);
removeItem('items', item);
Item item2 = new Item(item.state);
insert('items', i, item2);
}
Of course that isn't great either because fireItemUpdate cannot be called more than once (because it removes the original run from the list).
Upvotes: 4
Views: 293
Reputation: 657268
You need to make items
a property
@property final List<Item> items = [];
Upvotes: 3