Shailen Tuli
Shailen Tuli

Reputation: 14171

Observable field and text input in polymer

I have a class field that is a String and I want to use a text input to modify that field. How can I use @observable with polymer.dart to do this?

Here is the class field I would like to sync-up with the UI:

class Person {
  @observable String name;
  Person(this.name);
}

Upvotes: 1

Views: 913

Answers (1)

Shailen Tuli
Shailen Tuli

Reputation: 14171

Import the polymer.dart file and mix in the ObservableMixin into Person. Extend PolymerElement, and also use a @CustomTag annotation.

Here is what the dart file using @observable with a custom element could look like:

import 'package:polymer/polymer.dart';

class Person extends Object with ObservableMixin {
  @observable String name;
  Person(this.name);
}

@CustomTag("custom-element")
class CustomElement extends PolymerElement {
  @observable Person person = new Person('John');
}

In the associated .html file, use {{}} syntax to create the binding with the @observable field:

<!DOCTYPE html>

<html>
  <body>
    <polymer-element name="custom-element">
      <template>
        <label> Name: <input value="{{person.name}}"></label>
        <p>The name is {{person.name}}</p>
      </template>

      <script type="application/dart" src="element.dart"></script>
    </polymer-element>
  </body>
</html>

This element can be used in the following manner (note the link to boot.js):

 <!DOCTYPE html>

<html>
  <head>
    <title>index</title>
    <link rel="import" href="element.html">
    <script src="packages/polymer/boot.js"></script>
  </head>

  <body>
    <custom-element></custom-element>
    <script type="application/dart">
      void main() {}
    </script>
  </body>
</html>

Upvotes: 4

Related Questions