已发布属性的Dart Polymer元素:如何避免自我通知



我有一个自定义的Polymer元素,它具有已发布的属性inputValue

组件侦听inputValue的更改,并在更改时将新值报告给内部逻辑。

同样的操作方向相反:元素侦听内部逻辑变化,并将新值设置为inputValue

当新值设置为inputValue时,这会使观察系统通知所有侦听器,但元素本身就是侦听器。

我希望避免元素被通知自己所做的更改。

这里的自定义元素Dart代码:

@CustomTag("codemirror-input")
class CodemirrorInput extends PolymerElement {
  @published
  String mode;
  @published
  String inputValue;
  CodemirrorInput.created() : super.created();
  void ready() {
    Map options = {
      'mode':  mode
    };
    GradeCodeMirror editor = new GradeCodeMirror.fromElement(
        $['codemirror'], options: options);
    onPropertyChange(this, #inputValue, (){
      editor.setOption("value", inputValue);
    });
    editor.onChange.listen((_){
      inputValue = editor.getDoc().getValue();
    });
  }
}

我想知道,如果值实际上没有改变,为什么inputValueChanged会触发,我认为只有当旧值和新值不同时才会触发。但如果它真的不起作用,你可以自己检查

editor.onChange.listen((_){
  var val = editor.getDoc().getValue();
  if(inputValue != val) {
    inputValue = val;
  }
});
onPropertyChange(this, #inputValue, (){
  editor.setOption("value", inputValue);
});

可以通过在元素中添加一种方法来简化

void inputValueChanged(oldValue, newValue) {
  editor.setOption("value", inputValue);
}

每次inputValue更改时都会调用此方法。

最新更新