Pregunta

My final objective is don't have to write HTML like this:

<div id='counter'>
     {{counter}}
  </div>

  <div>
     <button
        id="startButton"
        on-click="{{start}}">
        Start
     </button>
     <button
        id="stopButton"
        on-click="{{stop}}">
        Stop
     </button>
     <button
        id="resetButton"
        on-click="{{reset}}">
        Reset
     </button>
</div>

I would like to know if it is possible to create a Polymer-element without using HTML. For example I tried this:

@CustomTag('tute-stopwatch')
class TuteStopWatch extends PolymerElement {

ButtonElement startButton,
  stopButton,
  resetButton;

  @observable String counter = '00:00';

  TuteStopWatch.created() : super.created() {
    createShadowRoot()..children = [
      new DivElement()..text = '{{counter}}',

      new DivElement()..children = [
        startButton = new ButtonElement()..text = 'Start'
           ..onClick.listen(start),
        stopButton = new ButtonElement()..text = 'Stop'
           ..onClick.listen(stop),
        resetButton = new ButtonElement()..text = 'Reset'
           ..onClick.listen(reset)
      ]
    ];
  }
}

Previous code creates HTML and shadow root correctly, but it doesn't create the binding between the @observable counter and the text of the DivElement.

I know that this is caused because I am trying to create the shadow root after the element has been instantiated/created. So that I should create the template of the element in other place before the template has been bound with its observable.

¿Fue útil?

Solución

You can write a manual data binding like this:

   changes.listen((changes) {
     for (var change in changes) {
        if (change.name == #counter) {
           myDivElement.text = change.newValue;
        }
     }
   });

changes is a property of the Observable class, which PolymerElement mixes in. (This is difficult to see in the API reference, as it currently doesn't show a class' mixins or the mixed in properties and methods.)

Polymer seems to be mostly about enabling declarative html based bindings. It may be worth exploring using custom elements and shadow dom directly, as you're not really using polymer for anything in this example. To do this you need to change the class definition to:

   class TuteStopWatch extends HtmlElement with Observable {
     ...
   }

And register your element with document.register(). You also need to include the polymer.js polyfill for custom elements.

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