【问题标题】:Dart Polymer element with published property: how to avoid self-notification具有已发布属性的 Dart Polymer 元素:如何避免自我通知
【发布时间】:2014-10-30 00:03:28
【问题描述】:

我有一个自定义 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();
    });
  }
}

【问题讨论】:

  • 我仍然很难理解这里发生了什么。您不能只从您的代码中更新value 并让 Polymer 解决更新问题吗?是什么让editor.onChange.listen 火了?
  • Codemirror 是一个外部库,它封装了一个 DIV 并使其成为提供语法高亮的源代码编辑器。我正在使用该 JS 库的移植到 Dart。当用户在源代码编辑器中修改代码时,codemirror 编辑器会触发 editor.onChange.listen。
  • 这和value绑定的一样吗?
  • 我正在使用 value 属性(现在已修复并重命名 inputValue)作为外部数据绑定的桥梁。

标签: dart dart-polymer observable


【解决方案1】:

我想知道为什么 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改变时都会调用这个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多