Tuesday, January 21, 2014

Dynamically Binding Polymer Values into Angular Applications


Must. Stop. Dart.

I am getting too far ahead of myself while researching Patterns in Polymer. For the most part, I try to keep the Dart and JavaScript investigation in sync. But recently I pushed straight through SVG and on into Angular research with Dart. I really need to work my way back to do both in JavaScript (and to write new chapters on both).

But darn it, Seth Ladd pointed out the angular_node_bind package and… ooh, shiny!

But really, I think that packages answers a need that I had for extracting data from my <x-pizza> Polymer for use in the containing the Angular application:



I start with the usual, adding angular_node_bind to the list of my application's dependendencies in pubspec.yaml:
name: angular_example
dependencies:
  angular: any
  polymer: any
  angular_node_bind: any
dev_dependencies:
  unittest: any
transformers:
- polymer:
    entry_points:
    - web/index.html
While reading through the angular_node_bind example code, I notice an alternate syntax for initializing a Polymer-powered Angular application. After last night, I already know that I have to manually start the Polymer platform with initPolymer() in my application's main() entry point:
main() {
  initPolymer();

  var store = new AngularModule()
    ..type(RouteInitializer, implementedBy: StoreRouter);

  ngBootstrap(module: store);
}
But it seems that it may be more proper to perform that initialization inside a Polymer run():
main() {
  initPolymer().run((){

    var store = new AngularModule()
      ..type(NodeBindModule)
      ..type(RouteInitializer, implementedBy: StoreRouter);

    ngBootstrap(module: store);
  });
}
Even better, the new Angular.dart way of doing things seems to be running those type() injects inside a proper constructor:
class StoreModule extends Module {
  StoreModule() {
    type(NodeBindDirective);
    type(RouteInitializer, implementedBy: StoreRouter);
  }
}

main() {
  initPolymer().run((){
    ngBootstrap(module: new StoreModule());
  });
}
However it is done, that should give me what I want: angular binding to my Polymer attributes. So I test this out in my customizing pizza page. The double square brackets should bind an expression for me:
<h3>Oooh! Let's make beautiful pizza together</h3>

<pre>[[ pizza ]]</pre>

<p>
  <x-pizza pizzaState="[[ pizza ]]"></x-pizza>
</p>
But, when I load the page up, I am getting a nice old stacktrace:
Class 'DynamicExpression' has no instance getter 'assignable'.

NoSuchMethodError : method not found: 'assignable'
Receiver: Instance of 'DynamicExpression'
Arguments: []

STACKTRACE:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      NodeBindDirective.NodeBindDirective (package:angular_node_bind/angular_node_bind.dart:61:24)
#2      _LocalClassMirror._invokeConstructor (dart:mirrors-patch/mirrors_impl.dart:795)
#3      _LocalClassMirror.newInstance (dart:mirrors-patch/mirrors_impl.dart:736)
#4      DynamicInjector.newInstanceOf (package:di/dynamic_injector.dart:44:35)
#5      _TypeProvider.get (package:di/module.dart:142:29)
#6      Injector._getInstanceByType.<anonymous closure> (package:di/injector.dart:118:31)
#7      _defaultCreationStrategy (package:di/module.dart:106:34)
#8      Injector._getInstanceByType (package:di/injector.dart:116:23)
#9      Injector._getInstanceByType (package:di/injector.dart:124:7)
#10     Injector.get (package:di/injector.dart:173:47)
...
And I cannot quite figure this one out.

Update: I was able to get this working with a simple change to angular_node_bind. With that, I can update my Polymer <x-pizza> and see the changes in my Angular application:



Phew! That's a load off my mind. With that, I think I am safe going back to JavaScript-ify this SVG / Angular application.


Day #1,003

Monday, January 20, 2014

Observable Polymers in Angular Applications


It seems that I may have been a tad premature in thinking that I had the Dart versions of Angular and Polymer working together. To be sure, most of it is working. The Angular routing it successfully navigating between a simple start page and the page that contains my Polymer. The Polymer is sufficiently registered that it shows up on that second page:



But that turns out to be the extent of it. Even though the Polymer is starting enough to display, none of its buttons and menus are doing what they are supposed to be doing: building a pizza. At first I suspected that Angular was somehome seizing control of the various template bindings. The answer turns out to be much more mundane.

For whatever reason, I continue to use two Polymer lifecycle methods, ready() and enteredView(), interchangeably. They are not interchangeable—the developers would not bothered to create them if they were. And, in fact, this seems to be the use case in which they distinguish themselves. When I normally develop a Polymer, it is the only thing on the page. The Polymer is “ready” in this case when the Polymer has entered the view.

In my Angular application, however, the Polymer is ready when it and the Angular code load on the first page. By the time the next Angular route is accessed, the Polymer has been ready, left the view (resulting in observers going away), and brought back without re-registering things. Happily, the solution is to use the correct lifecycle method:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created();
  enteredView() {
    super.enteredView();
    model = new Pizza()
      ..changes.listen(updatePizzaState);

    updatePizzaState();
  }
  // ...
}
That gets me a little closer, but things are still not updating when I make changes to the underlying model in the Polymer. I suspect that this is yet another case of Observable not updating in raw Dart. When I work with plain old Polymer, I work around this problem with a Dart Pub transformer.

When I got started with this Angular and Polymer combination, I purposefully removed the transformer to reduce the number of moving parts. In an attempt to get Observables working again, I restore the transformer in pubspec.yaml:
name: angular_example
dependencies:
  angular: any
  polymer: any
dev_dependencies:
  unittest: any
transformers:
- polymer:
    entry_points: web/index.html
Now, when I start up pub serve, I get loads of errors:
➜  dart git:(master) ✗ pub serve
Serving angular_example on http://localhost:8080
[Warning from polymer (Linter) on angular_example|web/partials/custom.html]:
web/partials/custom.html:4:3: definition for Polymer element with tag name "x-pizza" not found.
[Warning from polymer (Linter) on angular_example|web/index.html]:
web/index.html:22:7: definition for Polymer element with tag name "ng-view" not found.
...
There are a bunch more, but I eventually realize that those are just the usual dart2js warnings and errors. Hopefully those are just what they seem—linter warnings that do not have any real bearing.

But when I load my Angular application, I receive a very worrisome error:
Exception: InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. (Dartium)
Worrisome, but apparently not devastating: the application, including observable (and buildable) <x-pizza> elements, now works:



That is not quite the end of it as this does not appear to work when compiled to JavaScript, but I leave that puzzle for another day.



Day #1,002

Sunday, January 19, 2014

Day 1,001: Getting Started with Angular and Polymer (Dart)


Up today, I start experimenting with Angular.dart and Polymer.dart. For tonight, I would like to start with a simple Angular application and see what, if anything, I need to do in order to use my amazing <x-pizza> Polymer:



I actually need to go back and fix that Polymer up some, but I think the learning ground is more fertile at this point with Angular than with refactoring or converting to JavaScript. Still, I do need to do both before <x-pizza> is Patterns in Polymer worthy. Anyway…

Angular. I love it. I am probably a horrible person to ask an opinion on libraries and frameworks. Most people seem to be absolutely certain that some are better than others. I am unable to make decisions like that until I work with a library enough that it starts to affect how I think about other tools. By that time, I have almost always found some great use-cases for the tool at hand, leaving me hard pressed to dislike outright.

So, for a guy that co-authored Recipes with Backbone and who still loves coding in Backbone.js, I also love Angular. Mostly I am glad to know both as I think they have overlap, but also different use-cases.

The use case that I would like to explore in Angular tonight is an online pizza store. I have an <x-pizza> Polymer, which seems like it could be put to nice use throughout such an app.

I start with a pubspec.yaml that includes both the Angular and Polymer packages, but does not include the usual Polymer transformer:
name: angular_example
dependencies:
  angular: any
  polymer: any
dev_dependencies:
  unittest: any
# transformers:
# - polymer:
#     entry_points: web/index.html
I am unsure how the transformer would interact with Angular, so I leave that out of the equation tonight.

While working with raw Polymer, I have needed to include initialization code in the web page:
    <!-- Load component(s) -->
    <link rel="import" href="packages/angular_example/elements/x-pizza.html">
    <!-- Load Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
I do not think that will work in an Angular application, which needs to spin itself up without another Dart script gumming up the works. I don't think that will work, but I am not positive. To find out for sure, I set up my page with both Angular and Polymer initialization (Angular stuff goes in main.dart):
<!DOCTYPE html>
<html ng-app lang="en">
  <head>
    <title>Pizza Store</title>

    <script type="application/dart" src="main.dart"></script>

    <!-- Load component(s) -->
    <link rel="import" href="packages/angular_example/elements/x-pizza.html">
    <!-- Load Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
  <body>
    <div class="container">
      <h1>Dart Bros. Pizza Shoppe</h1>
      <ng-view></ng-view>
    </div>
  </body>
</html>
But, when I load that page, I see the following in the console:
[ERROR] Only one Dart script tag allowed per document
Bother. But not too much of a bother.

Back when I was learning to test Polymer, I needed to initialize Polymer without using that script. That turned out to be pretty easy. Instead of exporting that one script, I import the Polymer packages into my main.dart Angular app and invoke initPolymer:
import 'package:polymer/polymer.dart';
import 'package:angular/angular.dart';
import 'package:angular/routing/module.dart';
import 'package:angular_example/store.dart';

main() {
  initPolymer();

  var store = new AngularModule()
    ..type(RouteInitializer, implementedBy: StoreRouter);

  ngBootstrap(module: store);
}
In addition to removing the export, I also need to ensure that the usual <link> imports of Polymer elements occur before the main.dart script:
<!DOCTYPE html>
<html ng-app lang="en">
  <head>
    <title>Pizza Store</title>
    <link rel="import" href="packages/angular_example/elements/x-pizza.html">
    <script type="application/dart" src="main.dart"></script>
  </head>
  <body>
    <div class="container">
      <h1>Dart Bros. Pizza Shoppe</h1>
      <ng-view></ng-view>
    </div>
  </body>
</html>
With that, I am ready to take a look at my Angular application. As I said, I am starting very simple here. So simple, in fact, that I have a router and nothing more. The router declares two pages: the default start page and the custom pizza builder page:
import 'package:angular/angular.dart';
import 'package:angular/routing/module.dart';

class StoreRouter implements RouteInitializer {
  Scope _scope;
  StoreRouter(this._scope);

  void init(Router router, ViewFactory view) {
    router.root
      ..addRoute(
          defaultRoute: true,
          name: 'start',
          enter: view('partials/home.html')
        )
      ..addRoute(
          name: 'custom-pizza',
          path: '/pizza/custom',
          enter: view('partials/custom.html')
        );
  }
}
I define my two partials. The home.html is a simple page that links to the route defined for building custom pizza:
<h3>This is the home of darty pizza</h3>

<p>
  Why not
 <a href="/pizza/custom">build your own, awesome pizza</a>!
</p>
When I first load the application, I see:



Similarly, I define the custom.html partial as:
<h3>Oooh! Let's make beautiful pizza together</h3>

<p>
  <x-pizza></x-pizza>
</p>
Which results in:



That was rather easy to get working! Of course, I have yet to do anything real with this. I am not taking advantage of any of Angular's features and would very much like to explore binding values from Polymers into Angular applications. But that is grist for another day. For tonight, I am quite happy with the progress so far.


Day #1,001

Saturday, January 18, 2014

Day 1000: Animated SVG in Polymer


For an ostensibly UI facing library, I have done almost no UI work while researching Patterns in Polymer. I think that speaks to the hidden power of coding with the library. Even so, it is a web based, UI library, so I ought to do some UI-like things. Enter last night's <x-pizza> tag—the SVG based pizza builder:



The pizza SVG in this Polymer is built by passing a “maker” function, which makes individual toppings (e.g. pepperoni), into add-topping methods:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  _addFirstHalfTopping(maker) {
    for (var i=0; i<20; i++) {
      var angle = 2 * PI * _rand.nextDouble();
      var u = _rand.nextDouble() + _rand.nextDouble();
      var distance = 125 * ((u < 1.0) ? u : 2-u);

      var topping = maker()
        ..attributes.addAll({
            'cx': "${150 - (distance * sin(angle)).abs()}",
            'cy': "${150 + (distance * cos(angle))}"
          });

      $['pizza-graphic'].append(topping);
    }
  }
  // ...
}
It is a little hard to randomly distribute things in a circle, but happily there is Stack Overflow, which is the source for most of that.

It is nice to see the pizza built and all, but I would like to give hungry buyers more of a sense of building their own pizzas. Animating the toppings coming in from the side and dropping onto the pizza should do that nicely. I have no idea if that is possible with SVG, but there is one way to find out...

I start by grouping the toppings in an SVG <g> element. It turns out that you cannot set cx and cy attributes on group elements. Instead you have to translate them in a transform (that's gonna be easy to remember):
  _addFirstHalfTopping(maker) {
    var group = new GElement()
      ..attributes = {'transform': 'translate(150,150)'};

    for (var i=0; i<20; i++) {
      var angle = 2 * PI * _rand.nextDouble();
      var u = _rand.nextDouble() + _rand.nextDouble();
      var distance = 125 * ((u < 1.0) ? u : 2-u);

      var topping = maker()
        ..attributes.addAll({
            'cx': "${-(distance * sin(angle)).abs()}",
            'cy': "${ (distance * cos(angle))}"
          });

      group.append(topping);
    }
    $['pizza-graphic'].append(group);
  }
I have my toppings grouped and can position them together. How about animating?

Unfortunately, the <animate*> tags do not seem to work too well when trying to dynamically start animations. The <animateMotion> tag almost works… some of the time… when you don't hit reload too fast or stare at the page funny:
  _addFirstHalfaTopping(maker) {
    // ...
    $['pizza-graphic'].append(group);
    group..append(
          new AnimateMotionElement()..attributes = {
            'from': '0, 150',
            'to':   '150, 150',
            'dur':  '3s',
            'fill': 'freeze'
          }
        );

  }
For whatever reason, that does not seem reliable and fails to work at all on Firefox. So it seems that I need to revisit my old friend requestAnimationFrame(). I have honestly been missing this since 3D Game Programming for Kids went to press, so I may be reaching for a golden hammer here. But I don't care, animation frames, which are functions that get called when the browser signals it is ready to paint, are cool.

It seems that Dart has a future-based take on animation frames. Given an animate() function, I can ask the browser to call it with window.animationFrame.then(animate). The function that animates pizza toppings sliding in from the side over the course of 1.5 seconds is then:
  _addFirstHalfaTopping(maker) {
    // ...
    $['pizza-graphic'].append(group);
    var start;
    int dur = 1500;
    animate(time) {
      if (start == null) start = time;
      if (time - start > dur) return;
      var x = 150 * (time - start) / dur;
      group.attributes['transform'] = 'translate(${x.toInt()}, 150)';

      window.animationFrame.then(animate);
    };
    window.animationFrame.then(animate);
  }
That does the trick. Just as with the JavaScript requestAnimationFrame(), I have to request the animate() function once and then recursively call it from within animate() afterwards to keep the animation running. The effect is a nice, smooth animation that starts with the toppings floating in from the side:



And settling down nicely:



For completeness' sake, I animate the toppings falling gently, like a mother putting a babe down to rest, at the end of the left-to-right animation:
  _addFirstHalfaTopping(maker) {
    // ...
    $['pizza-graphic'].append(group);
    var start_y;
    int dur_y = 500;
    animateY(time) {
      if (start_y == null) start_y = time;
      if (time - start_y > dur_y) return;

      var x = 150;
      var y = 140 + 10 * sin(0.5 * PI * (time - start_y) / dur_y);

      group.attributes['transform'] = 'translate(${x}, ${y.toInt()})';

      window.animationFrame.then(animateY);
    }

    var start_x;
    int dur_x = 1500;
    animateX(time) {
      if (start_x == null) start_x = time;
      if (time - start_x > dur_x) return window.animationFrame.then(animateY);
      // ...
    };

    window.animationFrame.then(animateX);
  }
My code has serious longer-than-my-arm code smell at this point, but it works!

I call it a night here. Up tomorrow either the JavaScript implementation of this SVG Polymer or, if that proves trivial, I will move on to playing with Angular and Polymer together.

Day #1000

Friday, January 17, 2014

Day 999: Polymer and SVG


I can't resist. The temptation to play around with SVG is simply too great and I am helpless before its wiles.
I really meant to start looking at incorporating Polymer elements in Angular. Perhaps tomorrow. Onto the SVG!

I have a pretty cool <x-pizza> Polymer that builds pizzas for ordering:



The problem, of course, is that the current pizza state is in the form of text. Saaaay! SVG can help with that!

I start by adding a blank SVG tag to my <x-pizza> template:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>

    <!-- <pre>{{pizzaState}}</pre> -->
    <div title="{{pizzaState}}">
      <svg version="1.1"
        baseProfile="full"
        id="pizza-graphic"
        style="display: block; margin: 10px auto"
        width="300" height="300"
        xmlns="http://www.w3.org/2000/svg">
      </svg>
    </div>
    <!-- ... -->
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
That creates a 300 by 300 blank SVG canvas on which to paint. I give it an ID so that I can readily look it up using the Polymer $ for automatic node finding.

I already have my Polymer updating the pizza state (text-only so far) when new items are selected from the various menus. To do so, the updatePizzaState() method is called by various change event handlers. I factor the old text-only code out into _updatePizzaText(). In addition to calling this method, I also have updatePizzaState() call my new, SVG powered _updateGraphic() method:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  updatePizzaState([_]) {
    _updateText();
    _updateGraphic();
  }

  _updateGraphic() {
    this.$['pizza-graphic'].innerHtml = '''
      <circle cx="150" cy="150" r="150" fill="tan" />
      <circle cx="150" cy="150" r="140" fill="darkred" />
      <circle cx="150" cy="150" r="135" fill="lightyellow" />
    ''';
  }
  // ...
}
There is not too much to _updateGraphic() so far. It adds three circles in the center of the 300 by 300 SVG element, each slightly smaller than the previous, each representing a different layer of the pizza (crust, sauce, and cheese). I use the $ node finder to ensure that I have the correct SVG element.

With that, I have SVG!



To add toppings, I need a generator for each of the supported toppings:
  _svgPepperoni() =>
    new CircleElement()..attributes = {'r': '10', 'fill': 'red'};
  _svgSausage() =>
    new CircleElement()..attributes = {'r': '3',  'fill': 'brown'};
  _svgGreenPepper() =>
    new CircleElement()..attributes = {'r': '10', 'fill': 'green'};
Next, I need a way to choose the appropriate SVG maker function given a string representing a topping:
  _toppingMaker(String topping) {
    if (topping == 'pepperoni') return _svgPepperoni;
    if (topping == 'sausage') return _svgSausage;
    if (topping == 'green peppers') return _svgGreenPepper;
  }
With that, I can iterate over each topping and add them to the pizza:
  _addWholeToppings() {
    model.wholeToppings.forEach((topping) {
      var maker = _toppingMaker(topping);
      _addWholeTopping(maker);
    });
  }
The maker now points to the appropriate generator function (e.g. _svgPepperoni). Armed with that, I can make 20 randomly placed toppings with:
  _addWholeTopping(maker) {
    var rand = new Random();
    for (var i=0; i<20; i++) {
      var topping = maker();
      topping.attributes
        ..['cx'] = "${150 + (90 * cos(PI * rand.nextDouble()))}"
        ..['cy'] = "${150 + (90 * cos(PI * rand.nextDouble()))}";
      $['pizza-graphic'].append(topping);
    }
  }
And that does the trick. The end result is:



So yeah, I need a better green pepper. And maybe some animation. And random placement probably isn't quite right. But it is definitely better than plain text. So, yay SVG!


Day #999

Thursday, January 16, 2014

Day 998: Binding to Model Changes in Polymer (Dart)


Tonight, I hope to better express what needs to update when the Pizza model changes in my <x-pizza> Polymer. The JavaScript version of Polymer has an observe block to do this, but I cannot find a Dart equivalent. I came up with a solution (and a pretty good one), but I do not know if it is the solution. And I must strive for the solution in Patterns in Polymer.

I currently have a simple model driven Polymer that updates the pizza state for display:



Sure, it could use some fancy graphics, but this is fine for illustration and exploration. When a human clicks the add topping buttons, the Polymer adds the selected ingredient to the model. By virtue of property change listeners, the change in the Pizza model results in an update to the current pizza state representation:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created() {
    model = new Pizza()
      ..firstHalfToppings.changes.listen(updatePizzaState)
      ..secondHalfToppings.changes.listen(updatePizzaState)
      ..wholeToppings.changes.listen(updatePizzaState);
    // ...
  }
  // ...
}
Thanks to the magic of Dart method cascades, I can establish change listeners for multiple properties on my model.

That is nice and all, but the three listeners seem a tad redundant. Really, I would be happier to listen for any changes anywhere in the model—not just changes to those individual properties. Something like that might be expressed as:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created() {
    model = new Pizza()
      ..changes.listen(updatePizzaState);
    // ...
  }
  // ...
}
I have to admit that this sort of feels like something that an Observable class ought to give me for free. That is, if any observable properties in an observable class change, then the instance changes too. But that is not the case, so I am going to need to manually do this for my Pizza class:
class Pizza extends Observable {
  ObservableList<String> firstHalfToppings = toObservable([]);
  ObservableList<String> secondHalfToppings = toObservable([]);
  ObservableList<String> wholeToppings = toObservable([]);
}
(I am not sure the word “observable” is in there enough)

Thankfully, manually notifying that the model has changed in Polymer is directly supported via the notifyChange() method. So, in the Pizza constructor, I listen to the change stream on the individual properties and, whenever such an event occurs, I notify the object itself that a change has occurred:
class Pizza extends Observable {
  ObservableList<String> firstHalfToppings = toObservable([]);
  ObservableList<String> secondHalfToppings = toObservable([]);
  ObservableList<String> wholeToppings = toObservable([]);

  Pizza() {
    firstHalfToppings.changes.listen((_)=> notifyChange(_));
    secondHalfToppings.changes.listen((_)=> notifyChange(_));
    wholeToppings.changes.listen((_)=> notifyChange(_));
  }
}
I think that is pretty close to the spirit of what I want to accomplish.

Still, I am surprised that there is nothing closer to observe blocks in the the JavaScript version of Polymer. These let me observe properties via dot notation, invoking the supplied callback when changes are observed:
  observe: {
    'model.firstHalfToppings': 'updatePizzaState',
    'model.secondHalfToppings': 'updatePizzaState',
    'model.wholeToppings': 'updatePizzaState'
  },
But if that exists, I am unable to find it.


Day #998

Wednesday, January 15, 2014

Day 997: Cascade Observers in Polymer (Dart)


I am usually pretty safe assuming that my assumptions are wrong. Unless they're not. Happily, this turned out to be the case with some code I was trying to force in Polymer.dart. Thanks to a reimplementation in the JavaScript version of the Polymer project, I now have a better understanding of bound variables in Polymer.

The problem arose when I tried to bind some Pizza model attributes in a <x-pizza> element:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
    <!-- ... -->
  </template>
  <script src="x_pizza.dart"></script>
</polymer-element>
Those attributes were not bound, at least not such that their changes were observed in the template. Interestingly, when an actual bound attribute, say a “pizza state” instance variable, was bound in the same <pre> element in my template, then the model attributes were updated:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{pizzaState}}
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
    <!-- ... -->
  </template>
  <script src="x_pizza.js"></script>
</polymer-element>
In fact, the model attributes in the template were updated whenever the pizzaState instance variable was updated. So it seems that including a truly bound variable inside a tag will force all bound variables—model or element—to update. That seems useful information to file away for another day.

For today, I would like to see how the JavaScript library's solution of path expressions to watch for changes in a model translates into Dart. From last night's JavaScript, the solution was to observe three list attributes in the model:
Polymer('x-pizza', {
  observe: {
    'model.firstHalfToppings': 'updatePizzaState',
    'model.secondHalfToppings': 'updatePizzaState',
    'model.wholeToppings': 'updatePizzaState'
  },
  // ...
});
The observe block tells Polymer to call the updatePizzaState() method (which updates pizzaState for the template) whenever a change is seen in any of those lists.

If there is an equivalent for the observe block in Polymer.dart, I cannot find it.

What I wind up using instead is simple change listeners. For this to work, the model in my Model Driven View, Pizza, needs to be “observable.” Furthermore, since the properties in question are lists, I need a specialized “observable” instance of those lists. Both of these are established with judicious used of the @observable annotation:
@observable
class Pizza {
  List<String> firstHalfToppings = toObservable([]);
  List<String> secondHalfToppings = toObservable([]);
  List<String> wholeToppings = toObservable([]);
}
With that, I can create something that looks like an observe block. If you squint:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  Pizza model;

  XPizza.created(): super.created() {
    model = new Pizza()
      ..firstHalfToppings.changes.listen(updatePizzaState)
      ..secondHalfToppings.changes.listen(updatePizzaState)
      ..wholeToppings.changes.listen(updatePizzaState);
    // ...
  }
 // ...
}
The double dot operator in Dart is a method cascade. It returns the original object instead of the return value of the method (or property lookup). Above, this allows me to ask for the firstHalfToppings, secondHalfToppings, and wholeToppings properties from the newly created Pizza object. For each of these, I listen to the changes stream for a change and update the “pizza state” accordingly.

And that does the trick:



I can live with that method cascade solution. At least for tonight. It is a solution (and a relatively clean one at that), but I am not 100% certain that it is the solution for this in Polymer.dart. While digging through class documentation, I came across Polymer's bind() and bindProperty() methods. Both use similar path expressions as those found in the JavaScript observe block. I am not entirely sure that they operate in the same problem space, but that is a topic for another day. Like tomorrow!


Day #997