多层次的双向数据绑定

时间:2017-10-16 12:15:44

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

我想在两个级别上访问纸张输入的值。不幸的是,这不起作用。这是我的最小例子:

<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>

当我更改纸张输入的内容时,更改将转发到text-block元素的blockValue,但不会转发到主要元素的_myValue。它似乎与约束力 block-value={{_myValue}}  还不够。我还需要做什么?

1 个答案:

答案 0 :(得分:1)

您需要使用blockValuetext-block元素中声明notify: true,否则父元素不会收到有关更改的通知:

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

Reference