使用自定义逻辑为 paper-input-container 设置默认值

Set a default value for paper-input-container with custom logic

我正在尝试重现聚合物演示 here. How can I set a default/initial value for paper-input-container with its ssn-input component inside? The running version is here 提供的社会安全号码示例。

我尝试将属性值添加到 paper-input-container 和 ssn-input,但它没有显示为初始默认值。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Polymer Element Test Case</title>
  <base href="//polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">

  <link rel="import" href="paper-input/paper-input-container.html">
  <link rel="import" href="paper-input/paper-input-error.html">
  <link rel="import" href="paper-input/demo/ssn-input.html">
</head>
<body>
   <paper-input-container always-float-label auto-validate attr-for-value="value">
          <label>Social Security Number</label>
          <ssn-input class="paper-input-input"></ssn-input>
          <paper-input-error>SSN invalid!</paper-input-error>
   </paper-input-container>
</body>
</html>

我检查了 <ssn-input>, and it seems to me that there is no code to split the provided value in its three substrings and provide it to the three paper-input. Instead when the user types something within the paper-inputs, each string becomes a _ssnX and a computeValue function links them together storing the result in the value property. Here the piece of code from ssn-input.html:

的原始实现
properties: {
  value: { notify: true, type: String },
  _ssn1: { type: String },
  _ssn2: { type: String },
  _ssn3: { type: String },

  validator: { type: String, value: 'ssn-validator' }
},
observers: [
  '_computeValue(_ssn1,_ssn2,_ssn3)'
],
_computeValue: function(ssn1, ssn2, ssn3) {
  this.value = ssn1.trim() + '-' + ssn2.trim() + '-' + ssn3.trim();
}

ssn-input是组件,读取用户输入的内容,将所有内容放入值属性中。因此,首先要做的就是初始化这个元素的value属性,如下:

<paper-input-container always-float-label auto-validate>
    <label>Social Security Number</label>
    <ssn-input class="paper-input-input" value="102-12-1233"></ssn-input>
    <paper-input-error>SSN invalid!</paper-input-error>
</paper-input-container> 

属性值初始化ssn-input中的相关属性。 ssn-input 具有三个内部 input 元素,用于显示和接受用户输入。因此,初始值必须在“-”字符上进行拆分。最好的地方是在 value 属性 观察者中。因此,修改后的 ssn-input 元素代码如下:

Polymer({
  is: 'ssn-input',

  behaviors: [
    Polymer.IronValidatableBehavior
  ],

  properties: {
    value: { notify: true, type: String, observer: '_handleValueChanged' },
    _ssn1: { type: String },
    _ssn2: { type: String },
    _ssn3: { type: String },
    validator: { type: String, value: 'ssn-validator' }
  },

  _handleValueChanged: function(value) {
    var arr = value.split("-");
    this._ssn1 = arr[0];
    this._ssn2 = arr[1];
    this._ssn3 = arr[2];
  },

  observers: [
    '_computeValue(_ssn1,_ssn2,_ssn3)'
  ],

  _computeValue: function(ssn1, ssn2, ssn3) {
    this.value = ssn1.trim() + '-' + ssn2.trim() + '-' + ssn3.trim();
  }
});

在这里,jsbin running example.