简体   繁体   中英

PolymerDart: Data binding templates with complex models

So I have a shared library with some models I intend to use on the server as well as the client:

library models;

class Model {
  String id;
}

class Theatre extends Model {
  String name;
  // implements List<E>
  CustomCollection<Movie> movies = new CustomCollection();

  Theatre(this.name);
}

class Movie extends Model {
  String name;
  Movie(this.name);
}

I have a Polymer element like this:

<polymer-element name="my-app">
  <template>
    <movie-list movies="{{theatre.movies}}"></movie-list>
    <button on-click="{{moreMovies}}">More movies!</button>
  </template>
  <script type="application/dart" src="my_app.dart"></script>
</polymer-element>

With the following code behind:

import 'package:polymer/polymer.dart';
import 'package:my_app/models.dart';

@CustomTag('my-app')
class MyApp extends PolymerElement {
  @observable theatre = new Theatre('Lucky Seven Cinema');

  void moreMovies(event, detail, sender) {
    theatre.movies.add(new Movie('The Goonies'));
  }
}

PolymerDart doesn't seem to observe my property changes: after the initial page load, changing theatre.name or adding or removing an item from theatre.movies does not result in the bindings updating. Polymer's documentation says that expressions are re-evaluated when the value of one or more paths in an expression changes .

If I go into models library and add @observable to all of my model properties, PolymerDart seems to pick up the changes, but now I've added a new dependency to my models library -- and I want this library to work both on the client and the server so I don't have to duplicate my logic.

Also, adding @observable to every possible property I might want to data bind is super overkill and pretty messy to look at.

I assume I'm doing something wrong here: what is it?

The model classes need to extend Observable and the properties need an @observable annotation. See Observe package from polymer dart for more details.

class model extends Observable {
  ...
}

class Theatre extends Model {
  @observable
  String name;
}

I can't tell how the implementation of your CustomCollection looks like but if it contains an embedded List or Map you should initialize it like List backingList = toObservable([]); so Polymer gets notified when elements are added/removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM