lgzaqg
Last Updated: February 25, 2016
·
363
· iaincampbell

Observing model changes in Polymer Dart

Polymer expressions can be tricky when bound to model properties. The docs on Observables aren't quite there, and there's lots of outdated information flying around the interwebs.

I was looking to alter the text on a button based on whether a model's id field was null or not.

<button on-click="{{save}}" type="button">
<template if="{{exists}}">Edit</template>
<template if="{{!exists}}">Add</template>
</button>

I initially had the following:

@observable
bool exists => !(id==null);

The thing is, no change events were being fired when the model properties were updated. It turns out that the solution is to bind to a dummy variable and update that by tracking changes to the model properties:

import 'package:polymer/polymer.dart';
import 'dart:mirrors';
import 'mymodel.dart';

@CustomTag(‘my-model-form’)
class MyModelForm extends PolymerElement {

  @observable MyModel model = new MyModel();
  @observable bool exists = false;  

  MyForm.created() : super.created();

  @override
  void attached() {
    model.changes.listen(_trackChanges);
    super.attached();
  }

  _trackChanges(changes) {
    changes.forEach((PropertyChangeRecord record) {
      if(MirrorSystem.getName(record.name)=='id')
        exists = !(record.newValue==null);        
    });
  }
}

A PropertyChangeRecord returns a List of Symbols so I needed the Mirror library to extract the actual field name.