Pregunta

Removing and re-adding a polymer element instance breaks the data bindings. Calling prepareElement() reconnects everything, but is this the best way?

Given this HTML, using the click-counter example

<body>           
  <click-counter id="click_counter_id" count="5"></click-counter>    
</body>

and the code

main() {
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((LogRecord rec) {   
    print('${rec.loggerName}: ${rec.level.name}: ${rec.time}: ${rec.message}');
  });

  initPolymer().run(() {

    Polymer.onReady.then((_) {            

      var elem = querySelector('#click_counter_id');
      var parent = elem.parent;

      elem.remove();         

      new Timer(new Duration(seconds:1), () {

        parent.children.add(elem);

        // This reconnects the bindings. Is it correct?
        (elem as PolymerElement).prepareElement();
      });
    });
  });            
}

everything seems ok. But then we get a warning logged:

polymer.events: FINE: event: [button].on-click => [click-counter].increment())
polymer.unbind: FINE: [click-counter] cancelUnbindAll
polymer.unbind: WARNING: [click-counter] already unbound, cannot cancel unbindAll
polymer.events: FINE: event: [button].on-click => [click-counter].increment())

Is there a better way to remove and re-add a polymer element instance?

¿Fue útil?

Solución

I have not tried it myself but it seems reasonable. I hope the author doesn't mind coping his answer from Detached observables when re-using element.

Having looked into the polymer.js information bit I have found that there is a cancelUnbindAll function which must be called when the element is created or a preventDispose property set to true.

For anyone that might need to do the same, in the Dart implementation you must call cancelUnbindAll in the leftView function after the super call, as follows:

void detached() {
    super.leftView();
    this.cancelUnbindAll(preventCascade: true);
}

Alternatively, you can simply override the preventDispose property in your custom element:

bool get preventDispose => true;

EDIT

There is also a preventDispose see https://github.com/Polymer/polymer/issues/312

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top