Pergunta

Problem: I have a dart file defining some data structures, which I need to use both for the client and for the server. I'd like to make these data structures observable with Polymer. However, the server cannot include the file because of Polymer, because Polymer includes dart:html.

Context: I am working on a client/server (REST-full) application, where I want the server to provide the data structures defined available as resources. The client should display these resources, and have the possibility to send the modifications to the server. For that, Polymer is invaluable.

The reason I want to have this library available for the server is that I want the server to be able to validate the resources to be stored.

Possible solutions:

I don't yet know the internals of Polymer enough, but if my data structures could inherit from Map, I could use toObservable in the client side code to make the data structure observable, but instead of accessing by dot notation, I'd have to access members by keys instead, making it rather fragile.

I was wondering if I could use mirrors.dart to add the observable annotation on the client.

Of course, managing duplicate code, is really not a solution.

Foi útil?

Solução

You can use the observe package.

With ChangeNotifier you initiate the change notification yourself by calling notifyPropertyChange when a value changes. The changes get delivered synchronously.

Observable needs dirtyCheck() to be called to deliver changes.

Polymer calls Observable.dirtyCheck() repeatedly to get the changes automatically.

an example for each

import 'package:observe/observe.dart';

class Notifiable extends Object with ChangeNotifier {
  String _input = '';

  @reflectable
  get input => _input;

  @reflectable
  set input(val) {
    _input = notifyPropertyChange(#input, _input, val + " new");
  }

  Notifiable() {
    this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
  }
}

class MyObservable extends Observable {
  @observable
  String counter = '';

  MyObservable() {
    this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
  }
}

void main() {
  var x = new MyObservable();
  x.counter = "hallo";
  Observable.dirtyCheck();

  Notifiable notifiable = new Notifiable();
  notifiable.input = 'xxx';
  notifiable.input = 'yyy';
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top