javascript - 多层次的双向数据绑定(bind)

标签 javascript polymer polymer-2.x paper-elements

我想访问两个级别的 paper-input 的值。不幸的是,这不起作用。这是我的最小示例:

<html>
<head>
  <base href="https://polygit.org/polymer+:master/webcomponents+:master/shadycss+webcomponents+:master/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="paper-input/paper-input.html">
</head>
<body>

<dom-module id="text-block">
  <template>
    <style>
      #input-test {
        width: 100%;
      }
    </style>

    <paper-input id="input-test" label="Test" value="{{blockValue}}"></paper-input>
  </template>

  <script>
      class TextBlock extends Polymer.Element {

          static get is() {
              return 'text-block';
          }

          static get properties() {
              return {
                  blockValue: {
                      type: String,
                      value: '',
                      observer: '_onBlockValueChanged'
                  }
              }
          }
          
          _onBlockValueChanged() {
            console.log('Block value changed');
            console.log(this.blockValue);
          }

      }

      customElements.define(TextBlock.is, TextBlock);
  </script>
</dom-module>

<dom-module id="my-element">

  <template>
    <text-block block-value="{{_myValue}}"></text-block>
  </template>


  <script>
      HTMLImports.whenReady(function() {
          class MyElement extends Polymer.Element {
              static get is() { return 'my-element'; }

              static get properties() {
                  return {
                      _myValue: {
                          type: String,
                          value: '',
                          observer: '_myValueChanged'
                      }
                  };
              }

              _myValueChanged() {
                  console.log('_myValue changed');
                  console.log(this._myValue);
              }


          }
          customElements.define(MyElement.is, MyElement);
      });

  </script>

</dom-module>

<my-element></my-element>

</body>
</html>

当我更改 paper-input 的内容时,更改将转发到文本 block 元素的 blockValue,但不会进一步转发到主元素的 _myValue。看来与 block 值={{_myValue}} 还不够。我还需要做什么?

最佳答案

您需要在 text-block 元素中使用 notify: true 声明 blockValue,否则父元素将不会收到通知变化:

blockValue: {
  type: String,
  value: '',
  notify: true,
  observer: '_onBlockValueChanged'
}

Reference

关于javascript - 多层次的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770121/

相关文章:

javascript - polymer 2 : Handle clicks on PaperCard header

javascript - 使用正则表达式的输出来提供函数

javascript - 翻译后递归清除 Canvas

javascript - 如何使用 node.js 中的请求以多部分形式数据发送对象

javascript - 在 polymer (pikadate) 中使用第三方依赖

cordova - 如何禁用 polymer 纸元件中的涟漪效应?

http - 可以通过 HTTPS 提供 Polymer 2.0 PWA 吗?

javascript - 为什么d3图表超出了图表区域的边界?

polymer - 在运行时重新定义 Polymer 元素

javascript - polymer 未捕获的 DOMException