Dart: @observable of getters

邮差的信 提交于 2019-12-18 07:00:25

问题


I am trying to understand how observable getters work when they use other class instance properties:

When I bind the implicit getter/setter pair 'name' it updates in the input and in the div and everything is synced nicely.

However the explicit getter 'fullname' is not updating in the HTML. Is there a way to make that work (basically the 'fullname' in the element binding should update as well)?? Maybe I am missing a setter, but then again setter does not make sense here...

Very simple example to demonstrate:

test-element.html

<link rel="import" href="../../packages/polymer/polymer.html">
<polymer-element name="test-element">
  <template>
    <input value="{{ds.name}}">
    <div>{{ds.name}}</div>
    <div>{{ds.fullname}}</div>
  </template>
  <script type="application/dart" src="test1.dart"></script>
</polymer-element>

test-element.dart

import 'package:polymer/polymer.dart';
import 'package:popoli/sysmaster-settings.dart';

@CustomTag('test-element')
class TestElement extends PolymerElement {
  @observable VerySimpleTest ds;

  TestElement.created() : super.created() {
    ds = new VerySimpleTest()..name = 'Peter';
  }
}

ds.dart

class VerySimpleTest extends Observable {
  @observable String name = '';
  @observable String get fullname => 'Test: $name';
  VerySimpleTest() : super();
}

回答1:


You need to notify Polymer that a value has changed the getter depends on.

String set name(String val) {
  name = notifyPropertyChange(#fullname, name, val);
}

or this should work too

@ComputedProperty('Test: $name') String get fullname => 'Test: $name';

See http://japhr.blogspot.co.at/2014/08/the-polymerdart-computedproperty.html for more details.




回答2:


Some minor adaptations on Günter’s proposal make it work for me:

class VerySimpleTest extends Observable {
    String _name = '';
    //  @observable  // apparently, not even required
    String get name => _name;
    //  @observable  // apparently, not even required
    String get fullname => 'Test: $name';

    set name(String val) {
        String oldVal = _name;
        _name = notifyPropertyChange(#name, oldVal, val);
        _name = notifyPropertyChange(#fullname, oldVal, val);
    }
}


来源:https://stackoverflow.com/questions/28345560/dart-observable-of-getters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!