How to observe simple variable in dart language
Asked Answered
I

2

7

My question is: How to observe changes on simple variable like String or num? I know that you can easy observe object like this:

observe(t, (e) => print ("Value changed"));

but How to do this on simple variable?

Integrated answered 30/8, 2013 at 13:38 Comment(0)
V
7

(This answer applies to Polymer.dart.)

The observe package includes a wrapper for single observable values: ObservableBox.

import 'package:observe/observe.dart';
import 'dart:async';

void main() {
  ObservableBox myValue = new ObservableBox('hello');

  myValue.changes.listen((List<ChangeRecord> records) {
    PropertyChangeRecord record = records[0] as PropertyChangeRecord;

    print('${record.field} changed, it is now ${myValue.value}');
  });

  new Timer.periodic(const Duration(seconds: 1), (t) {
    myValue.value = new DateTime.now();
  });
}

There is no way to observe a top-level or function-scope single string, boolean, int, or double without using ObservableBox.

If the string, boolean, int, or double is a field of a class, you can use ObservableMixin and the @observable annotation.

class Foo extends Object with ObservableMixin {
  @observable String bar = '';
}

You can then get notified when an instance of Foo changes:

foo.changes.listen((List<ChangeRecord> records) {
  // ...
});
Vestigial answered 31/8, 2013 at 7:12 Comment(2)
It appears that currently (SDK 1.6) it's name rather than field, and oldValue and newValue. However, name is a Symbol, and so record.name == "myProperty" won't evaluate. Hrm.Petrina
So record.name == "myProperty" needs to be converted to a String using mirrors. See my answer and code below.Petrina
G
2

Here is an example of the binding of a string value that is object attribute:

<!DOCTYPE html>

<html>
  <head>
    <title>index</title>
    <script src="packages/polymer/boot.js"></script>
  </head>

  <body>
    <template id="_template" bind>
      <input type="text" value="{{name}}">
      <p>The name is {{name}}</p>
    </template>

    <script type="application/dart" src="index.dart"></script>
  </body>
</html>
import 'dart:html';
import 'package:polymer/polymer.dart';

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

main() {
  query("#_template").model = new Person('Bob');
}
Gordongordy answered 30/8, 2013 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.