Polymer.dart数据绑定:更新模型值而不更新视图

时间:2014-10-23 22:17:08

标签: dart dart-polymer

我有一个像这样的元素:

<polymer-element name="content-editable" attributes="value">
  <template>
    <div contenteditable="true" on-input="{{updateValue}} id="#editor">{{value}}</div>
  </template>
  <script type="application/dart" src="content_editable.dart"></script>
</polymer>

使用这样的代码隐藏:

@CustomTag('content-editable')
class ContentEditable {
  @published String value;
  ContentEditable.created(); : super.created();

  // This event handler is called every time the content of #editor changes.
  void updateValue(event, detail, sender) {
    // This code will update [value] -- which will then overwrite the contents of #editor!
    // That will reset the cursor position and other undesired behaviors.
    value = sender.text
  }
}

在AngularDart中,他们有一个&#34;模型&#34;机制。使用它的代码如下所示:

Model model;
void updateValue(event, detail, sender) {
  // This code tells everyone watching for changes on Model.value that its value has changed,
  // but it will NOT cause the template to re-render the value for #editor.
  model.valueView = sender.text;
}

如何设置ContentEditable.value而不会导致Polymer立即重置#editor的内容?

1 个答案:

答案 0 :(得分:1)

这是 解决方案,我讨价还价。鉴于其尴尬和对实验性聚合物功能的依赖,我希望它不是“解决方案”:

HTML:

<polymer-element name="content-editable" attributes="value">
  <template>
    <div contenteditable="true" on-input="{{updateValue}} id="#editor">
      <!-- use Polymer's _experimental_ one time binding syntax -->
      [[value]]
    </div>
  </template>
  <script type="application/dart" src="content_editable.dart"></script>
</polymer>

代码背后:

@CustomTag('content-editable')
class ContentEditable {
  @published String value;
  ContentEditable.created(); : super.created();

  void attached() {
    var editor = $['editor'];
    // v == List<PropertyChangeRecord>
    // expand the list so that where is called once per PropertyChangeRecord
    // this comment exists only for StackOverflow readers!
    this.changes.expand((v) => v).where((pcr) => pcr.name == #value).listen((pcr) {
      // An outside source updated value; naively repopulate editor content.
      if (editor.text != pcr.newValue) { editor.text = pcr.newValue; }
    });
  }

  void updateValue(event, detail, sender) {
    value = sender.text
  }
}

这是一个糟糕的解决方案,因为每次触发'input'事件时都必须遍历整个更改列表,以便查看事件的起源。您可以忽略内部更改事件(毕竟,您已完成此操作),但您无法忽略外部更改事件(文档已远程更新等)。理想的解决方案是隐式忽略内部事件,这样您就不会花时间迭代更改事件流。

相关问题